Ranges in Ruby

Ranges are a special data type in Ruby that represent a sequence of values. They are a powerful tool to iterate over a series of values ​​and to generate arrays.

Creating ranges: Link to heading

  • They are declared using a colon (..) between two values.
  • The first value is the lower limit of the range.
  • The second value is the upper limit of the range.
  • The range includes both limits.

Example: Link to heading

(1..6) # Range from 1 to 6 inclusive

Conversion to arrays: Link to heading

  • They can be converted to arrays using the to_a method.
  • This can be useful for working with range values ​​in other data structures.

Example: Link to heading

(1..6).to_a # => [1, 2, 3, 4, 5, 6]

Exclusive ranges: Link to heading

  • Exclusive ranges can be created using three points (…).
  • The range does not include the upper limit.

Example: Link to heading

(1...6) # Range from 1 to 5 (not including 6)

Lettered ranges: Link to heading

Ranges can be created with letters or any other character.

Example: Link to heading

("a".."z").to_a # => ["a", "b", "c", ..., "y", "z"]

Iteration over ranges: Link to heading

each can be used to iterate over the values ​​in the range.

Example: Link to heading

(1..6).each do |x|
    puts x

Operations with ranges: Link to heading

  • Mathematical operations can be performed with ranges.
  • The result will be a new range with the modified values.

Example: Link to heading

(1..6) + 5 # => (6..11)

In summary, ranges are a versatile tool for working with sequences of values ​​in Ruby. Their simplicity and efficiency make them a fundamental part of the language.

Keep learning about ranges to take full advantage of their benefits in your programs!

Additional Tips: Link to heading

  • You can use the & operator to intersect two ranges.
  • You can use the operator | to join two ranges.
  • Can you use the include method? to check if a value is within a range.

Example: Link to heading

(1..5) & (3..7) # => (3..5)
(1..5) | (3..7) # => (1..7)
(1..5).include?(3) # => true

Keep experimenting with ranges to create more efficient and expressive programs!

<< Cycles in Ruby Regular Expressions in Ruby >>