Skip to content
instance method

Range#%

(::Numeric | ::int n) -> ::Enumerator[Elem, self]
(::Numeric | ::int n) { (Elem element) -> void } -> self
%(n) {|element| ... } → self
%(n) → enumerator or arithmetic_sequence

Same as step (but doesn’t provide default value for n). The method is convenient for experssive producing of Enumerator::ArithmeticSequence.

Example
array = [0, 1, 2, 3, 4, 5, 6]

# slice each second element:
seq = (0..) % 2 #=> ((0..).%(2))
array[seq] #=> [0, 2, 4, 6]
# or just
array[(0..) % 2] #=> [0, 2, 4, 6]

Note that due to operator precedence in Ruby, parentheses are mandatory around range in this case:

Example
(0..7) % 2 #=> ((0..7).%(2)) -- as expected
0..7 % 2 #=> 0..1 -- parsed as 0..(7 % 2)
See also .new #== .json_create #=== also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0