如何从ruby中的数组中选择随机项(而不是rails)

时间:2012-12-06 23:32:47

标签: ruby arrays random

我有一系列国家:

@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'调用#`。

2 个答案:

答案 0 :(得分:30)

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

答案 1 :(得分:3)

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