给出如下字符串:
string = "hotdog cat food pickle sock ring lock fist door"
随机选择4项(以空格分隔)的正确方法是什么。所以我可以回来:
result = "fist_sock_food_cat"
由于
答案 0 :(得分:10)
您可以使用String#split
和Array#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("_")