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, ]
item = numbers[rand(numbers.length)]
puts item
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.
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
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
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 .
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?
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
How to Call Shell Commands from Ruby and Capture Output
Learn how to run shell commands in Ruby, capture output, check exit status, and choose the right method for scripts and apps.
How to Check Whether a String Contains a Substring in Ruby
Learn how to check if a string contains a substring in Ruby using include?, match, and multiline string examples.
How to Check if a Hash Key Exists in Ruby
Learn how to check whether a specific key exists in a Ruby hash using key?, has_key?, and include? with clear examples.