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

chrisaiv on 10/15/07


Tagged

Randomize


Versions (?)


Ruby: Randomly selecting an item from within a Hash


Published in: Ruby 


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

  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 

You need to login to post a comment.