Skip to content
Tags

, ,

key and value arrays to hash

December 13, 2012

An elegant way to generate a hash from two separate arrays of keys and values:


1.9.3-p194 :003 > keys = ['length', 'breadth', 'height']
=> ["length", "breadth", "height"]
1.9.3-p194 :004 > values = [10, 20, 30]
=> [10, 20, 30]
1.9.3-p194 :005 > keys.zip(values)
=> [["length", 10], ["breadth", 20], ["height", 30]]
1.9.3-p194 :006 > Hash[keys.zip(values)]
=> {"length"=>10, "breadth"=>20, "height"=>30}

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: