Turning array values into hash keys


/ Published in: Ruby
Save to your folder(s)

Useful for speeding up searches.


Copy this code and paste it in your HTML
  1. # a is the array we want to turn into a hash
  2. Hash[*a.zip([true] * a.size).flatten]
  3.  
  4. # Example:
  5. people= %w[John Mary Paul]
  6. query_people=Hash[*people.zip([true] * people.size).flatten]
  7.  
  8. query_people["John"] # returns true
  9. query_people["Wenceslas"] # returns nil (equivalent to false in most tests)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.