我有一系列国家:
@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'调用#`。
答案 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
。