![]() |
VOOZH | about |
Prerequisite: Ruby | Ranges
Ruby provides a Range class. Ruby ranges depict a set of values with a beginning and an end. Values of a range can be numbers, characters, strings or objects. It is constructed using start_point..end_point, start_point…endpoint literals, or with ::new. It provides the flexibility to the code and reduce the size of code. You can also create a range by using Range.new. A range which contains ..(two dots) means running from the starting value to the end value inclusively and if a range contains ...(three dots) means it exclude the end value.
Example:
(1..6).to_a # Output= [1, 2, 3, 4, 5, 6] (1...6).to_a # Output= [1, 2, 3, 4, 5]
Note: In Ruby, Ranges can be created using the objects, as long as the objects can be compared using their <=> operator. To return the next object in sequence, it provides the support to the succ method.
new : This method is used to create a range from given start and end value. In this method, if the third parameter is false or excluded, the range includes end-object. Otherwise, it will omit.
Range.new(start, end, exclusive=false)
Example:
Output:
12..15
rng==obj-->true or false
true
rng===value --> true or false
Lower
rng.begin --> obj
3
rng.each{|j| block} --> rng40....41....42....43....44....45....
rng.end --> obj
9
rng.eql?(obj) --> true or false
true
rng.exclude_end? --> true or false
false
rng.first --> obj
3
rng.last --> obj
9
rng.member?(value) --> true or false
true
rng.include?(value) --> true or false
false
rng.step(n=1){|obj|block} --> rng
Reference: https://ruby-doc.org/core-1.9.3/Range.html