# IVR: Phone Tree with Ruby and Rails

![Logo of a phone with 'Dial Home' and 'The Extra-Terrestrial Phone Home Service'.](https://docs-resources.prod.twilio.com/3d12c38e81044caff67625bc678e07a0bef359fa5e60904079e51a493d42d25c.png)

This [Ruby on Rails](https://rubyonrails.org/) sample application is modeled after a typical call center experience with an IVR but with more [Reese's Pieces](https://en.wikipedia.org/wiki/Reese%27s_Pieces#ET:_The_Extra-).

Stranded aliens can call a phone number and receive instructions on how to get out of earth safely or call their [home planet](https://bit.ly/asogi) directly. In this tutorial we'll show you the key bits of code to make this work.

To run this sample app yourself, [download the code and follow the instructions on GitHub](https://github.com/TwilioDevEd/ivr-phone-tree-rails).

*[Read how Livestream](https://customers.twilio.com/906/livestream/) and [other companies](https://customers.twilio.com/?q=use_cases_applied\&c=CQAA) built IVR phone trees with Twilio. Find examples and sample code for many web languages on our [IVR application page](/docs/voice/interactive-voice-response).*

## Answering a Phone Call

To initiate the phone tree, we need to configure one of our Twilio numbers to send our web application an HTTP request when we get an incoming call.

[Click on one of your numbers](https://www.twilio.com/login?g=%2Fconsole%2Fphone-numbers%2Fincoming%3F\&t=98a31204d675661e83d6f3d24078fc1b9f3d6c8f85f0695f6c24ccb513fd05cf) and configure the Voice URL to point to our app. In our code the route will be `/ivr/welcome`.

![Twilio console showing IVR webhook configuration for phone number with HTTP POST method.](https://docs-resources.prod.twilio.com/92fe3569695f645baff545fe291e03587fce2919b2cc501dce7254c16f40e152.png)

If you don't already have a server configured to use as your webhook, [ngrok](https://www.twilio.com/blog/test-your-webhooks-locally-with-ngrok.html) is a great tool for testing webhooks locally.

With our Twilio number configured, we are prepared to respond to the Twilio request.

## Respond to the Twilio request with TwiML

Our Twilio number is now configured to [send HTTP requests](/docs/voice/twiml) to this controller method on any incoming voice calls. Our app responds with [TwiML](/docs/voice/twiml) to tell Twilio what to do in response to the message.

In this case we tell Twilio to [`Gather`](/docs/voice/twiml/gather) the input from the caller and [`Say`](/docs/voice/twiml/say) a welcome message.

```rb title="Respond with TwiML to gather an option from the caller" description="app/controllers/twilio_controller.rb"
# !mark(11:20)
require 'twilio-ruby'


class TwilioController < ApplicationController

  def index
    render plain: "Dial Me."
  end

  # POST ivr/welcome
  def ivr_welcome
    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: menu_path) do |gather|
      gather.say(message: "Thanks for calling the E T Phone Home Service. Please press 1 for
      directions. Press 2 for a list of planets to call.", loop: 3)
    end
    render xml: response.to_s
  end

  # GET ivr/selection
  def menu_selection
    user_selection = params[:Digits]

    case user_selection
    when "1"
      @output = "To get to your extraction point, get on your bike and go down
        the street. Then Left down an alley. Avoid the police cars. Turn left
        into an unfinished housing development. Fly over the roadblock. Go
        passed the moon. Soon after you will see your mother ship."
      twiml_say(@output, true)
    when "2"
      list_planets
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end

  end

  # POST/GET ivr/planets
  # planets_path
  def planet_selection
    user_selection = params[:Digits]

    case user_selection
    when "2"
      twiml_dial("+19295566487")
    when "3"
      twiml_dial("+17262043675")
    when "4"
      twiml_dial("+16513582243")
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end
  end

  private

  def list_planets
    message = "To call the planet Broh doe As O G, press 2. To call the planet
    DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To
    go back to the main menu, press the star key."

    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: planets_path) do |gather|
      gather.say(message: message, voice: 'Polly.Amy', language: 'en-GB', loop: 3)
    end

    render xml: response.to_s
  end

  def twiml_say(phrase, exit = false)
    # Respond with some TwiML and say something.
    # Should we hangup or go back to the main menu?
    response = Twilio::TwiML::VoiceResponse.new
    response.say(message: phrase, voice: 'Polly.Amy', language: 'en-GB')
    if exit
      response.say(message: "Thank you for calling the ET Phone Home Service - the
      adventurous alien's first choice in intergalactic travel.")
      response.hangup
    else
      response.redirect(welcome_path)
    end

    render xml: response.to_s
  end

  def twiml_dial(phone_number)
    response = Twilio::TwiML::VoiceResponse.new do |r|
      r.dial(number: phone_number)
    end

    render xml: response.to_s
  end
end
```

After reading the text to the caller and retrieving their input, Twilio will send this input to our application.

## Where to send the caller's input

The *gather's* [`action`](/docs/voice/twiml/gather) parameter takes an absolute or relative URL as a value. In our case, this is the `menu` route.

When the caller has finished entering digits, Twilio will make a `GET` or `POST` request to this URL including a `Digits` parameter with the number our caller chose.

After making this request, Twilio will continue the current call using the TwiML received in your response. Any TwiML verbs occurring after a `<Gather>` are unreachable, unless the caller doesn't enter any digits.

```rb title="Send caller input to the intended route" description="app/controllers/twilio_controller.rb"
# !mark(14)
require 'twilio-ruby'


class TwilioController < ApplicationController

  def index
    render plain: "Dial Me."
  end

  # POST ivr/welcome
  def ivr_welcome
    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: menu_path) do |gather|
      gather.say(message: "Thanks for calling the E T Phone Home Service. Please press 1 for
      directions. Press 2 for a list of planets to call.", loop: 3)
    end
    render xml: response.to_s
  end

  # GET ivr/selection
  def menu_selection
    user_selection = params[:Digits]

    case user_selection
    when "1"
      @output = "To get to your extraction point, get on your bike and go down
        the street. Then Left down an alley. Avoid the police cars. Turn left
        into an unfinished housing development. Fly over the roadblock. Go
        passed the moon. Soon after you will see your mother ship."
      twiml_say(@output, true)
    when "2"
      list_planets
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end

  end

  # POST/GET ivr/planets
  # planets_path
  def planet_selection
    user_selection = params[:Digits]

    case user_selection
    when "2"
      twiml_dial("+19295566487")
    when "3"
      twiml_dial("+17262043675")
    when "4"
      twiml_dial("+16513582243")
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end
  end

  private

  def list_planets
    message = "To call the planet Broh doe As O G, press 2. To call the planet
    DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To
    go back to the main menu, press the star key."

    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: planets_path) do |gather|
      gather.say(message: message, voice: 'Polly.Amy', language: 'en-GB', loop: 3)
    end

    render xml: response.to_s
  end

  def twiml_say(phrase, exit = false)
    # Respond with some TwiML and say something.
    # Should we hangup or go back to the main menu?
    response = Twilio::TwiML::VoiceResponse.new
    response.say(message: phrase, voice: 'Polly.Amy', language: 'en-GB')
    if exit
      response.say(message: "Thank you for calling the ET Phone Home Service - the
      adventurous alien's first choice in intergalactic travel.")
      response.hangup
    else
      response.redirect(welcome_path)
    end

    render xml: response.to_s
  end

  def twiml_dial(phone_number)
    response = Twilio::TwiML::VoiceResponse.new do |r|
      r.dial(number: phone_number)
    end

    render xml: response.to_s
  end
end
```

Now that we have told Twilio where to send the caller's input, we can look at how to process that input.

## The Main Menu: Process the caller's selection

If our caller chooses '1' for directions, we use the `twiml_say` helper method to respond with TwiML that will [`Say`](/docs/voice/twiml/say) directions to our caller's extraction point.

If the caller chooses '2' to call their home planet, we need to gather more input from them. We'll cover this in the next step.

If the caller enters anything else, we respond with a TwiML [`Redirect`](/docs/voice/twiml/redirect) to the main menu.

```rb title="Main menu and return instructions" description="app/controllers/twilio_controller.rb"
# !mark(22:40,68:83)
require 'twilio-ruby'


class TwilioController < ApplicationController

  def index
    render plain: "Dial Me."
  end

  # POST ivr/welcome
  def ivr_welcome
    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: menu_path) do |gather|
      gather.say(message: "Thanks for calling the E T Phone Home Service. Please press 1 for
      directions. Press 2 for a list of planets to call.", loop: 3)
    end
    render xml: response.to_s
  end

  # GET ivr/selection
  def menu_selection
    user_selection = params[:Digits]

    case user_selection
    when "1"
      @output = "To get to your extraction point, get on your bike and go down
        the street. Then Left down an alley. Avoid the police cars. Turn left
        into an unfinished housing development. Fly over the roadblock. Go
        passed the moon. Soon after you will see your mother ship."
      twiml_say(@output, true)
    when "2"
      list_planets
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end

  end

  # POST/GET ivr/planets
  # planets_path
  def planet_selection
    user_selection = params[:Digits]

    case user_selection
    when "2"
      twiml_dial("+19295566487")
    when "3"
      twiml_dial("+17262043675")
    when "4"
      twiml_dial("+16513582243")
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end
  end

  private

  def list_planets
    message = "To call the planet Broh doe As O G, press 2. To call the planet
    DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To
    go back to the main menu, press the star key."

    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: planets_path) do |gather|
      gather.say(message: message, voice: 'Polly.Amy', language: 'en-GB', loop: 3)
    end

    render xml: response.to_s
  end

  def twiml_say(phrase, exit = false)
    # Respond with some TwiML and say something.
    # Should we hangup or go back to the main menu?
    response = Twilio::TwiML::VoiceResponse.new
    response.say(message: phrase, voice: 'Polly.Amy', language: 'en-GB')
    if exit
      response.say(message: "Thank you for calling the ET Phone Home Service - the
      adventurous alien's first choice in intergalactic travel.")
      response.hangup
    else
      response.redirect(welcome_path)
    end

    render xml: response.to_s
  end

  def twiml_dial(phone_number)
    response = Twilio::TwiML::VoiceResponse.new do |r|
      r.dial(number: phone_number)
    end

    render xml: response.to_s
  end
end
```

That was only the main menu and the first option. If the caller chooses '2', we will take them to the Planet Directory in order to collect more input.

## The Planet Directory: Collect more input from the caller

If our callers choose to call their home planet, we will read them the planet directory. This is similar to a typical "company directory" feature of most IVRs.

In our TwiML response we use a `Gather` verb again to receive our caller's input. This time, the `action` verb points to the `planets` route, which will switch our response based on what the caller chooses.

The TwiML response we return for that route uses a [`Dial`](/docs/voice/twiml/dial) verb with the appropriate phone number to connect our caller to their home planet.The current numbers are hardcoded, but we can also set those numbers using environment variables.

```rb title="Route users to a new phone number via the Planet Directory" description="app/controllers/twilio_controller.rb"
# !mark(42:74)
require 'twilio-ruby'


class TwilioController < ApplicationController

  def index
    render plain: "Dial Me."
  end

  # POST ivr/welcome
  def ivr_welcome
    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: menu_path) do |gather|
      gather.say(message: "Thanks for calling the E T Phone Home Service. Please press 1 for
      directions. Press 2 for a list of planets to call.", loop: 3)
    end
    render xml: response.to_s
  end

  # GET ivr/selection
  def menu_selection
    user_selection = params[:Digits]

    case user_selection
    when "1"
      @output = "To get to your extraction point, get on your bike and go down
        the street. Then Left down an alley. Avoid the police cars. Turn left
        into an unfinished housing development. Fly over the roadblock. Go
        passed the moon. Soon after you will see your mother ship."
      twiml_say(@output, true)
    when "2"
      list_planets
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end

  end

  # POST/GET ivr/planets
  # planets_path
  def planet_selection
    user_selection = params[:Digits]

    case user_selection
    when "2"
      twiml_dial("+19295566487")
    when "3"
      twiml_dial("+17262043675")
    when "4"
      twiml_dial("+16513582243")
    else
      @output = "Returning to the main menu."
      twiml_say(@output)
    end
  end

  private

  def list_planets
    message = "To call the planet Broh doe As O G, press 2. To call the planet
    DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To
    go back to the main menu, press the star key."

    response = Twilio::TwiML::VoiceResponse.new
    response.gather(num_digits: '1', action: planets_path) do |gather|
      gather.say(message: message, voice: 'Polly.Amy', language: 'en-GB', loop: 3)
    end

    render xml: response.to_s
  end

  def twiml_say(phrase, exit = false)
    # Respond with some TwiML and say something.
    # Should we hangup or go back to the main menu?
    response = Twilio::TwiML::VoiceResponse.new
    response.say(message: phrase, voice: 'Polly.Amy', language: 'en-GB')
    if exit
      response.say(message: "Thank you for calling the ET Phone Home Service - the
      adventurous alien's first choice in intergalactic travel.")
      response.hangup
    else
      response.redirect(welcome_path)
    end

    render xml: response.to_s
  end

  def twiml_dial(phone_number)
    response = Twilio::TwiML::VoiceResponse.new do |r|
      r.dial(number: phone_number)
    end

    render xml: response.to_s
  end
end
```

That's it! We've just implemented an IVR phone tree that will delight and serve your customers.

## Where to Next?

If you're a Ruby developer working with Twilio, you might enjoy these other tutorials:

[Automated Survey](https://www.twilio.com/blog/automated-survey-ruby-rails)

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

[Click-to-call](/docs/voice/sdks/javascript/get-started)

Click-to-call enables your company to convert web traffic into phone calls with the click of a button.
