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 …)”

  1. php usort | JZ * LABS - the web experiment playground of jason ting Says:

    [...] is a bit similar to ranges in Ruby where the objects you’re comparing have to be comparable with the [...]

Leave a Reply