We Recommend

Beginning Ruby: From Novice to Professional Beginning Ruby: From Novice to Professional
Beginning Ruby is a thoroughly contemporary guide for every type of reader wanting to learn Ruby, from novice programmers to web developers to Ruby newcomers. It starts by explaining the principles behind object-oriented programming and within a few chapters builds toward creating a genuine Ruby application.


Posted By

jarnaldich on 04/05/08


Tagged

array hash


Versions (?)


Turning array values into hash keys


Published in: Ruby 


Useful for speeding up searches.


  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 

You need to login to post a comment.