Ruby Ruby Loops Ruby Loops Loop Conditionals

Don't get this

Using a loop construct, assign the value of the get_answer() method to an answer variable. Use the break keyword to exit the loop if the answer variable is equal to the string e. Assume get_answer() is already written.

loop.rb
# Assume get_answer() is already defined
loop do
  print "Enter an answer ("e" to exit): "
  answer = gets.chomp
  break if answer == "e"
  end

2 Answers

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

Hi Marguerite! There are a few problems here, and some of them have to do with following the instructions of the challenge. It's always a good idea to not do anything the challenge doesn't specifically ask for. In this case, you've printed a line and then used gets.chomp to get the answer. However, neither of these are required nor expected by the challenge.

Take a look:

loop do
  answer = get_answer()
  if answer == "e"
    break
  end
end

Here we start our loop. As indicated by the instructions and the comment already available in the code, the value of answer will be provided by calling the function get_answer. Now, if answer is equal to "e", the loop will break. Then we end our if statement. Then we end our loop.

Hope this helps! :sparkles:

edited for additional note

Alexander Davison is correct. The if statement in combination with the break can be shortened to break if answer == "e". I have edited my answer to reflect this.

Also, a little note to Jennifer, just FYI Ruby has a shortcut.

Ruby lets you shorten this:

if answer == "e"
    break
end

To this:

break if answer == "e"

Try it in the IRB and they should work the same :)

Just a little note

~alex

Jennifer Nordell
Jennifer Nordell
Treehouse Staff

Thanks, I actually didn't know you could shorten that line that way (or didn't remember). Excellent point!

Cool! Also, like many other languages, Ruby also has a Ternary Operator that I use even more often.

You might know how it works because it is supported in many languages including JavaScript.

Here's the ternary operator in action:

# This program has no purpose it is just a demo. LOL

random_number = 5

# Note: no need for the parentheses it just looks a little nicer to me :)
food = (random_number == 5 ? "apple" : "orange")

If you wanted to write that same thing the regular way, you would have to do this:

random_number = 5

if random_number == 5
    food = "apple"
else
    food = "orange"
end

Here's how the ternary operator works:

  1. First you specify the condition.
  2. Next, you put a question mark. This is like asking a question.
  3. Then, you put your first value (Ruby will pick this value if the condition is true)
  4. Next, put a colon. This is like saying else.
  5. Lastly, put another value. If the condition is false, Ruby will pick this value.

I hope this helps! ~alex

Thanks for your input and explaining the ternary operator.

No problem :)