How to Sample a Random Element from Array in Ruby
In Ruby, you can sample a random element from an array using the
sample method. For example, array.sample returns one random element from array. This method is simple and built-in for arrays.Syntax
The sample method is called on an array to get random elements.
array.sample: Returns one random element.array.sample(n): Returns an array ofnunique random elements.
This method does not change the original array.
ruby
array.sample array.sample(n)
Example
This example shows how to get one random element and multiple random elements from an array.
ruby
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'] # Get one random fruit random_fruit = fruits.sample puts "Random fruit: #{random_fruit}" # Get three unique random fruits random_fruits = fruits.sample(3) puts "Three random fruits: #{random_fruits.join(', ')}"
Output
Random fruit: banana
Three random fruits: cherry, apple, date
Common Pitfalls
Some common mistakes when sampling from arrays include:
- Using
sample(n)withnlarger than the array size, which returns fewer elements without error. - Expecting
sampleto modify the original array; it does not. - Using
randwith array indexing manually, which is more complex and error-prone.
ruby
arr = [1, 2, 3] # Wrong: asking for more elements than exist puts arr.sample(5) # returns all elements without error, but fewer than 5 # Right: check size before sampling n = 5 sampled = arr.sample([n, arr.size].min) puts sampled
Output
[1, 2, 3]
[1, 2, 3]
Quick Reference
| Method | Description | Example |
|---|---|---|
| array.sample | Returns one random element | ['a', 'b', 'c'].sample # => 'b' |
| array.sample(n) | Returns an array of n unique random elements | ['a', 'b', 'c'].sample(2) # => ['c', 'a'] |
| array.sample(0) | Returns an empty array | ['a', 'b'].sample(0) # => [] |
Key Takeaways
Use
array.sample to get one random element from an array.Use
array.sample(n) to get multiple unique random elements.sample does not change the original array.Avoid requesting more elements than the array size with
sample(n).Using
sample is simpler and safer than manual random indexing.