ruby - When is an enumerator useful? -
an enumerator
object can created calling methods without passing block, example array#reject:
(1..3).reject.to_a # => [1, 2, 3]
is rule of ruby easier chaining or there other way pass behavior enumerator?
is rule of ruby easier chaining
yes, reason exactly. easy chaining of enumerators. consider example:
ary = ['alice', 'bob', 'eve'] records = ary.map.with_index |item, idx| { id: idx, name: item, } end records # => [{:id=>0, :name=>"alice"}, {:id=>1, :name=>"bob"}, {:id=>2, :name=>"eve"}]
map
yields each element with_index
, slaps item index on top of , yields block. block returns value with_index
, returns map
(does thing, mapping, and) returns caller.
Comments
Post a Comment