Ruby 2.7 adds beginless range

1 minute read

Ruby 2.7 adds beginless range .

Beginless Range

We can now use Beginless Range in Ruby 2.7.

# define an array a = ( 1 .. 10 ). to_a => [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] # In ruby 2.6 or earlier a [ 0 .. 2 ] => [ 1 , 2 , 3 ] # In Ruby 2.7.0 a [ .. 2 ] => [ 1 , 2 , 3 ] a [ ... 2 ] => [ 1 , 2 ]

In case statements, we can use startless range to express “below this value”.

case created_at when ... 2 . months . ago puts "old" when 2 . months . ago ... Date . today puts "recent" when Date . today .. puts "upcoming" end

It can be used to define constants in a similar way:

# Exam Scores CLASSES = { .. 33 => :fail , 34 .. 49 => :third , 50 .. 59 => :second , 60 .. 65 => :first , 66 .. => :first_with_distinction }

We can use beginless ranges in DSLs as well.

# Get the list of items whose price is less than or equal to 200 > Item . where ( price: .. 200 ) Item Load ( 0.2 ms ) SELECT "items" . * FROM "items" WHERE "items" . "price" <= ? LIMIT ? [[ "price" , 200 ], [ "LIMIT" , 11 ]] #<ActiveRecord::Relation [#<Product id: 1, price: 200, name: "Item 1", created_at: "2019-08-20 06:37:02", updated_at: "2019-08-20 06:37:02">, ...]> # Get the list of items whose price is less than 200 > Item . where ( price: ... 200 ) Item Load ( 0.2 ms ) SELECT "items" . * FROM "items" WHERE "items" . "price" < ? LIMIT ? [[ "price" , 200 ], [ "LIMIT" , 11 ]] #<ActiveRecord::Relation [#<Product id: 5, price: 100, name: "Item 5", created_at: "2019-08-20 06:37:29", updated_at: "2019-08-20 06:37:29">]>

Beginless range help out to get write DSL’s in a more natural way.