Explanation about Ruby Range object

What is a Range object?

An object that handles a range of values. For example, when expressing 1 to 3, it is expressed as follows.

irb(main):001:0> 1..3
=> 1..3
irb(main):002:0> (1..3).class
=> Range

You can also convert it to an 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 set 3 dots, you can create a Range object that does not include the last value.

irb(main):006:0> (1...3).to_a
=> [1, 2] 

You can also create a Range object for the alphabet.

irb(main):011:0> ('a'..'e').to_a
=> ["a", "b", "c", "d", "e"]

Retrieving the value of a Range object

Like an array, each method can be used to expand and retrieve each value.

irb(main):016:0> (1..5).each { |i| puts "#{i}" }
1
2
3
4
5
=> 1..5

Recommended Posts

Explanation about Ruby Range object
Explanation about Ruby String object
Explanation about Array object of Ruby
About Ruby and object model
[Ruby] About the difference between 2 dots and 3 dots of range object.
About Ruby symbols
About ruby ​​form
About Ruby Hashes
About Ruby arrays
About Ruby inheritance
About ruby block
About Ruby Hashes
About object orientation
About Ruby Symbols
About Ruby variables
About Ruby methods
About Ruby Kernel Module
About Ruby error messages
About Ruby exception handling
About Ruby Hashes (continued)
About eval in Ruby
[ruby] About here documents
About Ruby if statement
Ruby Learning # 31 Object Methods
About Ruby instance methods
[Ruby] About instance generation
About the [ruby] operator
Thinking about logic Ruby
[Swift] [Beginner]] About range operators
Ruby uppercase only specified range
[Ruby on Rails] about has_secure_password
About regular expressions in Ruby
About Ruby hashes and symbols
Ruby About various iterative processes
About the explanation about functional type
About Ruby classes and instances
About the behavior of ruby Hash # ==
Convert ruby object to JSON format
About Ruby single quotes and double quotes
About Ruby product operator (&) and sum operator (|)
[Super Introduction] About Symbols in Ruby
About object-oriented inheritance and about yield Ruby
[Ruby] Review about nesting of each