11

I have an array of countries:

@countries = ["Canada", "Denmark", "Germany", "Isle of Man", "Namibia", "Qatar", "South Africa",  "United Kingdom","United States"]

And am building some random data for testing like this:

@test = [{ :name   => "AAA -"+Faker::Name.name,  :country => @countries.???? ....}]

How do I get a random value from the @countries hash?

@countries.rand(mlen)

does not work and returns NoMethodError: private methodrand' called for #`.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Gary
  • 1,917
  • 3
  • 19
  • 19
  • 2
    For future reference, you should be referring to your data structure of countries as an `array` not a `hash`. – Andrew Hubbs Dec 06 '12 at 23:44
  • 1
    It's good to be familiar with all the methods in [Array](http://apidock.com/ruby/Array) and [Enumerable](http://apidock.com/ruby/Enumerable). It will save you a lot of effort and make your programs shorter! – Mark Thomas Dec 07 '12 at 01:23
  • Thanks - I got lost for a while. – Gary Feb 18 '14 at 03:35

2 Answers2

34

use Array#sample:

@countries = ["Canada", "Denmark", "Germany", "Isle of Man", "Namibia", "Qatar", "South Africa",  "United Kingdom","United States"]

random_country = @countries.sample
# => "Canada"

random_country = @countries.sample
# => "United Kingdom"
  • Works great thanks. I tried rand but this is a private method. Ruby has many hidden Gems. – Gary Dec 06 '12 at 23:40
  • For Ruby 1.8.7, it's [Array#choice](http://ruby-doc.org/core-1.8.7/Array.html#method-i-choice) – robd Mar 07 '14 at 15:08
4

You could also use random_country = @countries.shuffle.first.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
cluv
  • 620
  • 6
  • 11