Ranges in Ruby (and .. vs …)
Saturday 01/3/2009 – Category: Uncategorized
Ranges in Ruby are nifty: you can define a set by its start and end values and a range of values will be generated. This works "as long as the objects can be compared using their <=> operator and they support the succ method to return the next object in sequence."
Ranges created with .. will include the last value while those created with ... will exclude the last value. The syntax for this isn't the most intuitive, I had to go back to the docs to make sure I was using the right form.
A simple example:
(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(1...10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Date ranges using Merb and DataMapper:
(make sure to add the dm-helpers dependency for Rails-like date/time helpers)
yesterday = (Time.now-1.day).to_date
today = Date.today
@views_yesterday = Hit.count(:type => 'view', :created_at => yesterday..today)
Will yield all hits of type view that were created yesterday.
One Response to “Ranges in Ruby (and .. vs …)”
Leave a Reply
Recent Posts
- Good Word – now with definitions!
(Friday 03/5/2010 – 2 Comments) - Good Word – Words With Friends Word Checker
(Thursday 02/25/2010 – 31 Comments) - Facebook App Development gotchas
(Friday 02/19/2010 – No Comments) - StoreKit SKErrorUnknown
(Friday 02/19/2010 – 1 Comment)

February 10th, 2009 at 12:13 am
[...] is a bit similar to ranges in Ruby where the objects you’re comparing have to be comparable with the [...]