Can we take any element out of the array without using the length of the array?

Asked 2 years ago, Updated 2 years ago, 102 views

How do I spin random to extract any element from an array?

myarr = [1,6,43,82,3,68,9,2,1]

The same number is stored and you want to extract any number from this myarr. I'm using the arrangement length

myarr = [1,6,43,82,3,68,9,2,1]
item = myarr[rand(myarray.length)]

I'm writing like this, but I want to find out if I can use a more intuitive code.

array random ruby

2022-09-22 22:00

1 Answers

Ruby 1.9.1 and later have Array#sample.

puts [1,6,43,82,3,68,9,2,1].sample

If it's less than that,

"backports/1.9.1/array/sample".

Additional is required.

In addition, in version 1.8.7, there was a short time under the name choice, but it is not recommended to use it because of version compatibility


2022-09-22 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.