Question

How to Pick a Random Element from an Array in Ruby

rubyarraysrandom

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 sample means.
  • 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.first is like dumping out the whole bag, mixing every slip, and then taking the first one.
  • Using sample is 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.

Take Quiz

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:

  1. Ruby creates an array and stores three strings in fruits.
  2. fruits.sample asks Ruby to return one random element from that array.
  3. Ruby internally chooses one valid position.
  4. The chosen value is stored in choice.
  5. puts choice prints 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:

  1. fruits.length returns 3.
  2. rand(3) returns 0, 1, or 2.
  3. That number is stored in index.
  4. fruits[index] retrieves the element at that position.
  5. 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
Take Quiz

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:

  • myArray and myarray are 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:

  • sample returns nil
  • nil.upcase raises 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

ApproachExampleGood forNotes
samplemy_array.samplePicking one random elementMost idiomatic and readable
rand + indexmy_array[rand(my_array.length)]Manual controlWorks, but more verbose
shuffle.firstmy_array.shuffle.firstWhen you already need shuffled dataLess efficient for one item

sample vs shuffle.first

  • Use sample when you want one random element.
  • Use shuffle when you want the whole array in random order.

sample vs rand

  • Use sample for clarity.
  • Use rand when 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]}"
Take Quiz

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#sample is the idiomatic Ruby choice.
  • sample returns nil for an empty array.
  • sample(n) returns an array of up to n random elements.
  • Use shuffle only when you need a shuffled array.
  • Use rand when 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.

Take Quiz

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 sample to 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.
Take Quiz

Keep learning

Related questions

View more