user3675188
user3675188

Reputation: 7409

How do I convert array to hash, whose key is array value and value is index of the array

An array format is like following(the values won't duplicated in the array):

["ID", nil, "MO"]

I want to remove the nil, but the hash values should store the index in original array. Expected result:

{
  "ID" => 0,
  "MO" => 2
}

How could I do it in an elegant way?

Upvotes: 1

Views: 46

Answers (2)

Stefan
Stefan

Reputation: 114188

You can use Hash#delete to remove the pair with nil key:

hash = ["ID", nil, "MO"].each_with_index.to_h
hash.delete(nil)

Or as a one-liner:

["ID", nil, "MO"].each_with_index.to_h.tap { |h| h.delete(nil) }

Upvotes: 3

sawa
sawa

Reputation: 168131

["ID", nil, "MO"]
.each.with_index.with_object({}){|(e, i), h| h[e] = i unless e.nil?}
# => {"ID"=>0, "MO"=>2}

or

["ID", nil, "MO"]
.each.with_index.to_h.reject{|k, v| k.nil?}
# => {"ID"=>0, "MO"=>2}

Upvotes: 5

Related Questions