1

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?

1
  • Which index should be used for duplicates? The first? Or should the value be an array of indices? Commented Mar 26, 2015 at 10:13

2 Answers 2

5
["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}
Sign up to request clarification or add additional context in comments.

Comments

3

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) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.