Prev | Current Page 62 | Next

Brad Ediger

"Advanced Rails"

map(&b)
end
end
puts ("a".."f").map_with_index{|letter, i| [letter, i]}.inspect
# >> [["a", 0], ["b", 1], ["c", 2], ["d", 3], ["e", 4], ["f", 5]]
The enum_for method returns an Enumerator object whose each method functions like
the each_with_index method of the original object. That Enumerator object has
already been extended with the instance methods from Enumerable, so we can just
call map on it, passing the given block.
Enumerator also adds some convenience methods to Enumerable, which are useful to
have. Enumerable#each_slice(n) iterates over slices of the array, n-at-a-time:
(1..10).each_slice(3){|slice| puts slice.inspect}
# >> [1, 2, 3]
# >> [4, 5, 6]
# >> [7, 8, 9]
# >> [10]
Similarly, Enumerable#each_cons(n) moves a ???sliding window??? of size n over the collection,
one at a time:
(1..10).each_cons(3){|slice| puts slice.inspect}
# >> [1, 2, 3]
# >> [2, 3, 4]
# >> [3, 4, 5]
# >> [4, 5, 6]
# >> [5, 6, 7]
# >> [6, 7, 8]
# >> [7, 8, 9]
# >> [8, 9, 10]
Enumeration is getting a facelift in Ruby 1.9. Enumerator is becoming part of the core
language. In addition, iterators return an Enumerator object automatically if they are
not given a block. In Ruby 1.8, you would usually do the following to map over the
values of a hash:
hash.values.map{|value| ... }
This takes the hash, builds an array of values, and maps over that array. To remove
the intermediate step, you could use an Enumerator:
hash.


Pages:
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74