给出如下字符串:
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"