Chapters 14 & 15 - Web Apps

Exercise 1: Sinatra routes

The roll_die method below simulates rolling a die with the given number of sides. If you call roll_die(6), you’ll get a random number between 1 and 6. If you call roll_die(20), you’ll get a random number between 1 and 20.

Create three Sinatra routes that use this method:

  • The /roll/4 path should output “Rolling 4 sided die:”, followed by the result of calling roll_die(4).
  • The /roll/6 path should output “Rolling 6 sided die:”, followed by the result of calling roll_die(6).
  • The /roll/20 path should output “Rolling 20 sided die:”, followed by the result of calling roll_die(20).
require 'sinatra'

def roll_die(sides)
  rand(sides) + 1
end

get('/roll/4') do
  "Rolling 4 sided die: #{roll_die(4)}"
end

get('/roll/6') do
  "Rolling 6 sided die: #{roll_die(6)}"
end

get('/roll/20') do
  "Rolling 20 sided die: #{roll_die(20)}"
end

Once you have your server running, you can load any of these paths, and then refresh the browser repeatedly to get different random numbers.