iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💎
Understanding Ruby Range Objects
What is a Range object?
It is an object used to handle a range of certain values.
For example, to represent 1 to 3, you express it as follows:
irb(main):001:0> 1..3
=> 1..3
irb(main):002:0> (1..3).class
=> Range
You can also convert it into an array (Array) using a method called to_a.
irb(main):003:0> (1..3).to_a
=> [1, 2, 3]
irb(main):004:0> (1..3).to_a.class
=> Array
By the way, if you use three dots, you can create a Range object that excludes the final value.
irb(main):006:0> (1...3).to_a
=> [1, 2]
Additionally, you can generate Range objects for alphabets as well.
irb(main):011:0> ('a'..'e').to_a
=> ["a", "b", "c", "d", "e"]
Extracting values from a Range object
Similar to an array, you can use the each method to expand and extract each value.
irb(main):016:0> (1..5).each { |i| puts "#{i}" }
1
2
3
4
5
=> 1..5
Discussion