get a random element from an array in ruby

One way to get a random element from an array in Ruby is by using the sample method. The sample method returns a random element from the array. Here's an example:

main.rb
numbers = [1, 2, 3, 4, 5]
random_number = numbers.sample
puts random_number
76 chars
4 lines

This code will output one of the numbers in the array at random. The sample method can also be called with an argument to return multiple random elements from the array.

gistlibby LogSnag