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

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -