Chapters 14 & 15 - Web Apps

Exercise 3: Named parameters

Take your solution to Exercise 1, and convert the /roll/4, /roll/6, and /roll/20 routes to a single route that uses a named parameter for the number of sides. (You’ll need to convert the parameter from a string to an integer before passing it to the roll_die method.)

Before:

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

After:

require 'sinatra'

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

get('/roll/:sides') do
  sides = params['sides'].to_i
  "Rolling #{sides} sided die: #{roll_die(sides)}"
end