给出如下字符串:
string = "hotdog cat food pickle sock ring lock fist door"
随机挑选4个项目(用空格分隔)的正确方法是什么所以我可以回去:
result = "fist_sock_food_cat"
谢谢
最佳答案
您可以使用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"