有没有办法从数组中获取一个随机元素,并删除它只是单个元素

时间:2013-05-22 21:38:07

标签: ruby

我想:

1.9.3p392 :015 > a=["birds","things","people","people"]
 => ["birds", "things", "people","people"] 
1.9.3p392 :016 > a.sample
 => "people" 
1.9.3p392 :017 > a
 => ["birds", "things","people"] 
1.9.3p392 :018 >

但看起来样本不支持此功能。我在样本的论点中遗漏了什么?我知道我可以删除返回的内容但是会删除那些不仅仅是那个单一实例的成员。

THX

2 个答案:

答案 0 :(得分:2)

这是我最初提出的removes the element by index更传统的版本。此方法会改变原始数组,但也会保留顺序。

a = ["birds","things","people","people"]
i = rand(a.size)
# delete_at returns the element removed, or nil
elm = a.delete_at(i)

这是另一种没有副作用的解决方案(它使用one of the sample-size forms)。这种方法改变其余元素的顺序,对于大型数组可能“效率低”。

a = ["birds","things","people","people"]
elm, *rest = a.sample(a.size)

我实际上不会使用第二个解决方案,并且如果这是我想要的话,将首先手动复制数组 - 在审核之后,它似乎太“聪明”而且很复杂。

答案 1 :(得分:0)

你可以这样做:

a = ["birds","things","people","people"]
a.delete_at(a.find_index(a.sample))