Ruby/Range/As Iterator
Материал из Wiki.crossplatform.ru
Содержание |
each and each_with_index loop with range
(5..7).each {|x| print x } # Prints "567" (5..7).each_with_index {|x,i| print x,i } # Prints "506172"
each_cons loop with range
(1..5).each_cons(3) {|x| print x } # Prints "[1,2,3][2,3,4][3,4,5]"
each_slice loop with range
(1..10).each_slice(4) {|x| print x } # Prints "[1,2,3,4][5,6,7,8][9,10]"
When a range is used as an iterator, each value in the sequence is returned.
# So you can use a range to do things like create an array of digits: (1..9).to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9]