Rand method on array with use of range operator + array index

时间:2021-11-03 21:32:32

I have this little problem with this code: I want to pass parameter to this random_select method in form of array, and I want to have one random index returned. I know that It won't work due to the way that range operator works , for such purposes we have sample method. But can anyone explain me why is this code returning nil as one of its random value?

我对这段代码有这个小问题:我想以数组的形式将参数传递给这个random_select方法,我希望返回一个随机索引。我知道由于范围操作符的工作方式,它不起作用,为此目的,我们有样本方法。但任何人都可以解释我为什么这个代码返回nil作为其随机值之一?

def random_select(array)
   array[rand(array[0]..array[4])]
end

p random_select([1,2,3,4,5])

2 个解决方案

#1


1  

Because your range is accessing to array values, not to array indexes:

因为您的范围是访问数组值,而不是数组索引:

array = [1, 2, 3, 4, 5]
array[0] #=> 1
array[4] #=> 5
array[0]..array[4] #=> 1..5

What you want is achievable in this way:

你想要的是这样可以实现的:

def random_select(array)
  indexes = 0...array.size #=> 0...5
  array[rand(indexes)]
end

array = [1, 2, 3, 4, 5]
Array.new(100) { random_select array }.uniq.sort == array #=> true

#2


1  

Have you tried using sample?

你尝试过使用样品吗?

def random_select(array)
  array.sample
end

Choose a random element or n random elements from the array.

从数组中选择一个随机元素或n个随机元素。

The elements are chosen by using random and unique indices into the array in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements.

通过在数组中使用随机和唯一索引来选择元素,以确保元素不会重复,除非数组已包含重复元素。

If the array is empty the first form returns nil and the second form returns an empty array.

如果数组为空,则第一个表单返回nil,第二个表单返回一个空数组。

The optional rng argument will be used as the random number generator.

可选的rng参数将用作随机数生成器。

#1


1  

Because your range is accessing to array values, not to array indexes:

因为您的范围是访问数组值,而不是数组索引:

array = [1, 2, 3, 4, 5]
array[0] #=> 1
array[4] #=> 5
array[0]..array[4] #=> 1..5

What you want is achievable in this way:

你想要的是这样可以实现的:

def random_select(array)
  indexes = 0...array.size #=> 0...5
  array[rand(indexes)]
end

array = [1, 2, 3, 4, 5]
Array.new(100) { random_select array }.uniq.sort == array #=> true

#2


1  

Have you tried using sample?

你尝试过使用样品吗?

def random_select(array)
  array.sample
end

Choose a random element or n random elements from the array.

从数组中选择一个随机元素或n个随机元素。

The elements are chosen by using random and unique indices into the array in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements.

通过在数组中使用随机和唯一索引来选择元素,以确保元素不会重复,除非数组已包含重复元素。

If the array is empty the first form returns nil and the second form returns an empty array.

如果数组为空,则第一个表单返回nil,第二个表单返回一个空数组。

The optional rng argument will be used as the random number generator.

可选的rng参数将用作随机数生成器。