Peña, Botp
8/21/2008 8:40:00 AM
From: Brian Ross [mailto:p.brian.ross@gmail.com]=20
# I'd imagine that this would return map as a new hash with the=20
# keys modified. Is there anything like collect! for hashes?
the required pairings for hashes makes it fragile to implement a =
map/collect like feature similar to plain arrays.
you can create one if you like. just be careful.
eg, here is my simple-minded implementation,
irb(main):084:0> class Hash
irb(main):085:1> def map2
irb(main):086:2> h=3D{}
irb(main):087:2> self.each do |k,v|
irb(main):088:3* kk,vv=3Dyield(k,v)
irb(main):089:3> key =3D kk || k
irb(main):090:3> val =3D vv || v
irb(main):091:3> h[key] =3D val
irb(main):092:3> end
irb(main):093:2> h
irb(main):094:2> end
irb(main):095:1> end
=3D> nil
irb(main):096:0> hash.map2{|k,_| k.upcase}
=3D> {"NAME"=3D>"greg", "JOB"=3D>"boring", "HAIR"=3D>"plenty"}
irb(main):097:0> hash.map2{|k| k.upcase}
=3D> {"NAME"=3D>"greg", "JOB"=3D>"boring", "HAIR"=3D>"plenty"}
irb(main):098:0> hash.map2{|k,v| k.upcase}
=3D> {"NAME"=3D>"greg", "JOB"=3D>"boring", "HAIR"=3D>"plenty"}
irb(main):099:0> hash.map2{|k,v| [k.upcase,v.capitalize]}
=3D> {"NAME"=3D>"Greg", "JOB"=3D>"Boring", "HAIR"=3D>"Plenty"}
kind regards -botp