ruby .map! or each for modifying an array in place -
i have following:
article_results.keys |key| article_results[key].map! |a| a[:filename] = c.filename a[:sitename] = c.site_name end end
as want add each element of each array within hash dynamically, reason a[:filename]
, a[:sitename]
blank when used.
so want know if should using .each
instead. guess i'd know what's main difference since both can used side-effects.
i'm adding fyi, i'm using ruby 1.8.7 nice know how differs between versions (1.8.7 - 1.9+) well.
p.s. know difference between .each
, .map
is, i'm asking .map!
.
#map
has bit different semantics hashes has arrays (and think it's not consistent between versions of ruby). in general if looking array result of operation - #map
friend, if want hash result of operation - you're better off #reduce
:
article_results.reduce({}) |hash, (key, value)| hash.merge(key => value.merge(filename: c.filename, sitename: c.sitename)) end
alternatively if don't care how "functional" code is, can use #each
:
article_results.each |key, value| article_results[key].merge!(filename: c.filename, sitename: c.sitename) end
Comments
Post a Comment