djhworld djhworld - 5 months ago 48
Ruby Question

Array to Hash Ruby

Okay so here's the deal, I've been googling for ages to find a solution to this and while there are many out there, they don't seem to do the job I'm looking for.

Basically I have an array structured like this

["item 1", "item 2", "item 3", "item 4"]

I want to convert this to a Hash so it looks like this

{ "item 1" => "item 2", "item 3" => "item 4" }

i.e. the items that are on the 'even' indexes are the keys and the items on the 'odd' indexes are the values.

Any ideas how to do this cleanly? I suppose a brute force method would be to just pull out all the even indexes into a separate array and then loop around them to add the values.

Answer Source

Use to_h:

a = ["item 1", "item 2", "item 3", "item 4"]
h = a.to_h # => { "item 1" => "item 2", "item 3" => "item 4" }

For posterity, below is the answer for versions of ruby < 2.1.0:

a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }

That's it. The * is called the splat operator.

One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."

So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Ɓukasz Niemier (also in the comments) offers this method for large data sets:

h = Hash[a.each_slice(2).to_a]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download