Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我Array.sample用来从数组中返回一个随机元素。
Array.sample
然后我想获取该元素的索引以生成永久链接。有没有内置的方法来做到这一点?还是我需要自己动手?
我认为没有预先烘焙的解决方案,但您可以轻松地制作自己的解决方案。您可以sample在索引上使用:
sample
i = (0 .. a.length).to_a.sample e = a[i]
这为您提供了索引i和采样元素e。或者,由于您只是提取大小为 1 的样本,rand因此直接使用并跳过所有sample噪音:
i
e
rand
i = rand(a.length) e = a[i]
使用find_index怎么样?
如果你有:
my_array = [:foo,:qux]
你可以这样做:
my_sample = my_array.sample
进而:
my_index = my_array.find_index(my_sample)