如何从字符串中随机选择一定数量的项目,空格分隔?

时间:2017-01-17 02:09:32

标签: arrays ruby string ruby-on-rails-4

给出如下字符串:

string = "hotdog cat food pickle sock ring lock fist door"

随机选择4项(以空格分隔)的正确方法是什么。所以我可以回来:

result = "fist_sock_food_cat"

由于

2 个答案:

答案 0 :(得分:10)

您可以使用String#splitArray#sample

string
  .split     #=> ["hotdog", "cat", "food", "pickle", "sock", "ring", "lock", "fist", "door"]
  .sample(4) #=> ["ring", "pickle", "food", "fist"]
  .join('_') #=> "ring_pickle_food_fist"

答案 1 :(得分:1)

你也可以使用shuffle:

result = string.split.shuffle.first(4).join("_")