Question
I want to choose a random element from an array whose length can vary.
Normally, I would write something like this:
my_array = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc"]
item = my_array[rand(my_array.length)]
Is there a cleaner or more readable way to write the second line, or is this already the best approach?
I also thought about using:
my_array.shuffle.first
but I have only recently come across shuffle and have not used it in practice yet.
Short Answer
By the end of this page, you will understand the simplest and most idiomatic way to pick a random element from an array in Ruby. You will also learn how it compares with rand and shuffle, what happens with empty arrays, and how this pattern appears in real Ruby code.
Concept
In Ruby, the core concept behind this question is selecting a random element from a collection.
The most idiomatic way to do this in modern Ruby is:
my_array.sample
Array#sample was designed specifically for this purpose. It communicates intent clearly: you want one random item from the array.
Why this matters:
- Readability: other Ruby developers immediately understand what
samplemeans. - Less code: you do not need to manually generate an index.
- Fewer mistakes: you avoid off-by-one errors or indexing issues.
- Built-in behavior: Ruby handles the random selection logic for you.
Compare these approaches:
my_array[rand(my_array.length)]
This works, but it says: generate a random index, then use that index to access the array.
my_array.shuffle.first
This also works, but it shuffles the entire array just to take one item, which is more work than necessary.
my_array.sample
This is the clearest option because it directly expresses the goal.
In real programming, choosing the most direct method improves code quality. Good code is not just code that works; it is code that makes the intention obvious.
Mental Model
Think of an array like a bag of labeled slips of paper.
- Using
rand(my_array.length)is like first picking a numbered position in the bag, then finding the slip at that position. - Using
shuffle.firstis like dumping out the whole bag, mixing every slip, and then taking the first one. - Using
sampleis like simply reaching into the bag and pulling out one slip.
All three can give you a random item, but sample matches the task most naturally.
Syntax and Examples
Basic syntax
array.sample
This returns one random element from the array.
Example
languages = ["Ruby", "Python", "JavaScript", "Go"]
random_language = languages.sample
puts random_language
Possible output:
Python
Getting multiple random elements
sample can also return more than one element:
numbers = [1, 2, 3, 4, 5]
p numbers.sample(2)
Possible output:
[4, 1]
Compared with rand
numbers = [10, 20, 30, 40]
item = numbers[rand(numbers.length)]
puts item
This works, but it is more manual than needed.
Compared with shuffle.first
numbers = [10, 20, 30, 40]
item = numbers.shuffle.first
puts item
This is readable, but less efficient because Ruby shuffles the full array before taking the first element.
Empty array behavior
[].sample
This returns:
nil
That is useful, but you should handle it if your code expects a real value.
Step by Step Execution
Consider this code:
fruits = ["apple", "banana", "cherry"]
choice = fruits.sample
puts choice
Step by step:
- Ruby creates an array and stores three strings in
fruits. fruits.sampleasks Ruby to return one random element from that array.- Ruby internally chooses one valid position.
- The chosen value is stored in
choice. puts choiceprints that value.
A possible run might behave like this:
- Array contents:
['apple', 'banana', 'cherry'] - Randomly chosen element:
'banana' - Printed output:
banana
Now compare with the manual version:
fruits = ["apple", "banana", "cherry"]
index = rand(fruits.length)
choice = fruits[index]
puts choice
Step by step:
fruits.lengthreturns3.rand(3)returns0,1, or2.- That number is stored in
index. fruits[index]retrieves the element at that position.- The result is printed.
This is still valid, but it is doing extra steps that sample hides for you.
Real World Use Cases
Picking a random array element appears in many practical programs:
Simple app features
- Showing a random quote of the day
- Suggesting a random product or article
- Picking a random loading message
Games
- Choosing a random enemy type
- Selecting random loot or rewards
- Drawing a random card from a deck representation
Scripts and automation
- Picking a random test input
- Rotating through random prompts
- Selecting a random filename or task
APIs and web apps
- Returning a random greeting variation
- Serving a random featured item from a cached list
- Selecting a random fallback image
Example:
quotes = [
"Keep going.",
"Write code every day.",
"Small improvements add up."
]
puts quotes.sample
Real Codebase Usage
In real Ruby projects, developers usually prefer the method that best expresses intent. For random array selection, that is almost always sample.
Common pattern: direct selection
theme = ["light", "dark", "solarized"].sample
This is compact and clear.
Guarding against empty arrays
Because sample returns nil for an empty array, developers often use a guard clause:
def random_tag(tags)
return "untagged" if tags.empty?
tags.sample
end
Validation before use
user = users.sample
raise "No users available" if user.nil?
Using randomness in seeds or fixtures
statuses = ["draft", "published", "archived"]
post.status = statuses.sample
Avoiding unnecessary work
In production code, developers typically avoid this when only one item is needed:
items.shuffle.first
That pattern is more appropriate when you actually need a shuffled array.
Testing note
Random behavior can make tests flaky. In test code, developers may:
- stub randomness
- set a seed
- avoid random selection unless necessary
So while sample is excellent in application code, tests often need more control.
Common Mistakes
1. Using the wrong variable name
Ruby is case-sensitive.
Broken code:
myArray = ["a", "b", "c"]
item = myarray[rand(myArray.length)]
Problem:
myArrayandmyarrayare different names.
Correct code:
my_array = ["a", "b", "c"]
item = my_array.sample
2. Using inconsistent Ruby naming style
Ruby convention prefers snake_case.
Less idiomatic:
myArray = [1, 2, 3]
Preferred:
my_array = [1, 2, 3]
3. Shuffling the whole array unnecessarily
Broken approach for this use case:
item = my_array.shuffle.first
Why to avoid it:
- It does more work than needed.
- It is less direct than
sample.
Better:
item = my_array.sample
4. Forgetting about empty arrays
item = [].sample
puts item.upcase
Problem:
samplereturnsnilnil.upcaseraises an error
Safer version:
item = [].sample
puts item&.upcase || "No item found"
5. Overcomplicating random selection
Some beginners manually calculate index ranges when Ruby already provides a clear method.
Overcomplicated:
index = rand(0...my_array.length)
item = my_array[index]
Simpler:
item = my_array.sample
Comparisons
| Approach | Example | Good for | Notes |
|---|---|---|---|
sample | my_array.sample | Picking one random element | Most idiomatic and readable |
rand + index | my_array[rand(my_array.length)] | Manual control | Works, but more verbose |
shuffle.first | my_array.shuffle.first | When you already need shuffled data | Less efficient for one item |
sample vs shuffle.first
- Use
samplewhen you want one random element. - Use
shufflewhen you want the whole array in random order.
sample vs rand
- Use
samplefor clarity. - Use
randwhen you specifically need the random index itself.
Example where rand is useful:
index = rand(my_array.length)
puts "Selected position: #{index}"
puts "Selected value: #{my_array[index]}"
Cheat Sheet
# Pick one random element
array.sample
# Pick multiple random elements
array.sample(3)
# Manual version
array[rand(array.length)]
# Less efficient for one element
array.shuffle.first
Key points:
Array#sampleis the idiomatic Ruby choice.samplereturnsnilfor an empty array.sample(n)returns an array of up tonrandom elements.- Use
shuffleonly when you need a shuffled array. - Use
randwhen you need the random index, not just the value.
Example:
colors = ["red", "green", "blue"]
colors.sample
FAQ
What is the Ruby way to pick a random element from an array?
Use Array#sample:
my_array.sample
Is sample better than rand(array.length)?
For readability and intent, yes. rand is still valid, but sample is clearer.
Does sample modify the array?
No. It returns a random element without changing the original array.
What happens if the array is empty?
sample returns nil.
Should I use shuffle.first instead?
Usually no. It is fine technically, but it does extra work if you only need one element.
Can I get more than one random item?
Yes:
my_array.sample(2)
This returns an array of random elements.
Why do many Ruby examples use snake_case variable names?
Because snake_case is the standard Ruby naming convention and makes code more idiomatic.
Mini Project
Description
Build a simple Ruby script that displays a random message each time it runs. This demonstrates how to use Array#sample in a practical way and how to safely handle empty arrays.
Goal
Create a Ruby program that picks and prints a random message from an array.
Requirements
- Store at least five messages in an array.
- Use
sampleto select one random message. - Print the selected message to the console.
- Handle the case where the array is empty.
- Keep the code readable with Ruby naming conventions.
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.