Ruby多哈希随机值

时间:2014-02-10 15:57:10

标签: ruby random hash

countries = Hash[ "north" => "nl", "no", "uk" "south" => "sp", "fr", "it" "east" => "ru", "bl", "bg" ]

如何为每个元素(北,南,东)获取随机值?

非常感谢

2 个答案:

答案 0 :(得分:3)

以下是使用Array#sample的方法:

countries = {"north" => ["nl", "no", "uk"], "south" => ["sp", "fr", "it"], "east" => ["ru", "bl", "bg"] }
countries.map { |_,v| v.sample } # => ["nl", "it", "bg"]
countries.map { |_,v| v.sample } # => ["uk", "it", "bg"]

答案 1 :(得分:3)

替代Arup的答案。

countries = {"north" => ["nl", "no", "uk"], "south" => ["sp", "fr", "it"], "east" => ["ru", "bl", "bg"]}
countries.values.map(&:sample)
相关问题