Ruby: Randomly selecting an item from within a Hash


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

Needed a way to randomly select an item from within a Hash


Copy this code and paste it in your HTML
  1. #A. Create a Hash
  2. hash = {:key1 => "item1", :key2 => "item2", :key3 => "item3"}
  3. #B. Return a new array of all the Values from the Hash
  4. items = hash.values
  5. #C. Randomly
  6. puts items[rand(items.length)]

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.