Reputation: 7409
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
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
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