F
Farrel Lifson
Hi folks,
Array has got a pretty cool method zip which 'zips' two arrays together lik=
e so:
[1,2,3].zip([2,4,6])
=3D> [[1,2],[2,4],[3,6]]
That's also what you get when you call to_a on a Hash like
{1=3D>2,2=3D>4,3=3D>6}, so I thought why not add a method to Hash to do the
reverse, that is to construct a Hash from a zipped array?
class Hash
def Hash.from_zipped_array(zipped_array)
zipped_array.inject({}) do |hash,key_value_pair|
hash[key_value_pair[0]] =3Dkey_value_pair[1]
hash
end
end
end
# Example usage
animal =3D ["dog","cat",bird"]
sound =3D ["woof,"meow","cheep"]
make_a_sound_like_a =3D Hash.from_zipped_array(animal.zip(sound)
make_a_sound_like_a["dog"]
=3D>"woof"
Useful enough for inclusion?
Farrel
Array has got a pretty cool method zip which 'zips' two arrays together lik=
e so:
[1,2,3].zip([2,4,6])
=3D> [[1,2],[2,4],[3,6]]
That's also what you get when you call to_a on a Hash like
{1=3D>2,2=3D>4,3=3D>6}, so I thought why not add a method to Hash to do the
reverse, that is to construct a Hash from a zipped array?
class Hash
def Hash.from_zipped_array(zipped_array)
zipped_array.inject({}) do |hash,key_value_pair|
hash[key_value_pair[0]] =3Dkey_value_pair[1]
hash
end
end
end
# Example usage
animal =3D ["dog","cat",bird"]
sound =3D ["woof,"meow","cheep"]
make_a_sound_like_a =3D Hash.from_zipped_array(animal.zip(sound)
make_a_sound_like_a["dog"]
=3D>"woof"
Useful enough for inclusion?
Farrel