Skip to main content
Ruby

Randomly Selecting Items in a List using Ruby

By March 20, 2017No Comments

In this lesson, we are going to look at randomly selecting items in a list using Ruby. Like always we do try to keep examples as meaningful as possible whilst not becoming too complex. So today we are going to look at creating a weekly menu but randomly selecting items that you can cook. The list of items that we can cook will come from an Array that we statically populate but these easily could be populated from the command line or from a database query.

Create the Array

An array in Ruby is denoted by the [ ] brackets. We create a list for a five day week and to be generous we add in six items to choose from that we can cook.

can_cook = ["paella", "pizza", "fish pie", "chilli con carne", "beans on toast", "chicken schnitzel",]

Choose an Item

If we are randomly selecting items from a list using Ruby we can use the method sample from the Array class. We will feed the result into a variable called monday to represent Monday’s meal.

monday = can_cook.sample

Remove your Selection


It is possible, that for every day of the week the random selection could be the same. The point is that it is random. To ensure that we do not eat the same meal twice during the week we can delete the item from the array once it has been selected. Using the array’s delete method this is quite easy.

can_cook.delete(monday)

Create the Script

We can then continue to select the items for the rest of the week. However, we probably want some form of an iterator to run through the complete week for us. If we create a script with an array representing the meals that we can eat and an array for the days of the week we can soon have a running example.

#!/usr/bin/ruby
can_cook = ["paella",
        "pizza",
        "fish pie",
        "chilli con carne",
        "beans on toast",
        "chicken schnitzel",]
days_of_week = ["Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",]
days_of_week.each do |day|
        meal = can_cook.sample
        can_cook.delete(meal)
        puts "#{day} we will eat #{meal}"
end

For each day in the array days_of_week  we assign a meal and remove the meal from the available list. The week’s menu is then printed to the screen.

Leave a Reply