2012-12-06 25 views
9

我有个国家的数组:如何从红宝石阵列(未轨)选择一个随机项

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

和我建立了一些随机数据的测试是这样的:

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

如何从@countries散列中获得一个随机值?

@countries.rand(mlen) 

不起作用,并返回NoMethodError: private method rand'called for#`。

+1

为了将来的参考,您应该将您的国家数据结构称为'array'而不是'hash'。 –

+0

熟悉[Array](http://apidock.com/ruby/Array)和[Enumerable](http://apidock.com/ruby/Enumerable)中的所有方法是很好的。它会为你节省很多的精力,缩短你的程序! –

+0

谢谢 - 我迷了一阵子。 – Gary

回答

26

使用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" 
+0

非常感谢。我尝试过兰特,但这是一种私人方法。 Ruby有许多隐藏的宝石。 – Gary

+0

对于Ruby 1.8.7,它是[Array#choice](http://ruby-doc.org/core-1.8.7/Array.html#method-i-choice) – robd

3

你也可以使用random_country = @countries.shuffle.first