1

I am working on a lab for class about 'while' loops. This is the goal:

  • Create a variable and set it equal to true
  • While the variable you just created is true
  • Prompt user for number
  • Read in number
  • Compute double that number
  • Display double that number
  • Prompt the user if they want to go again
  • Read in that text
  • If that text input is “n” then set the true variable to false

This is the code I have:

puts "Enter a number"
x = Float(gets.chomp())

product = x * 2
puts "Double your number is"
puts product

while
  puts "Go again   y/n?"
  answer = gets.chomp
  if answer != 'y'
  end
end

The directions seem clear, but I don't understand how to turn it into code.

Any modifications will help.

8
  • 1
    Hint #1: "Create a variable and set it equal to true." Commented Oct 18, 2017 at 19:44
  • Hint #2: "While the variable is true". See this on how to properly write a while loop. Commented Oct 18, 2017 at 19:47
  • Hint #3: Everything that is supposed to happen "while the variable is true" needs to go inside the while loop. Commented Oct 18, 2017 at 19:50
  • 1
    Note that in Ruby the style is generally x = gets.chomp.to_f where empty argument lists are omitted and force-casting with things like Float() is strongly discouraged. Commented Oct 18, 2017 at 20:10
  • 1
    @Stefan In C++, PHP and others you'd write (float) x where that converts x to a float. Naturally some people think that the equivalent in Ruby would be Float(x), since as far as syntax goes thats' the closest, but it's actually x.to_f due to the principle of Duck Typing. In other words, any object that can handle a .to_f call is an acceptable value, not necessarily one that plays nice with Float. Commented Oct 19, 2017 at 16:18

1 Answer 1

1

You need to have a boolean flag to check at while level each loop:

again = true

while again
  puts "Enter a number "
  x = Float(gets.chomp())

  product = x * 2
  puts "Double your number is"
  puts product 

  puts "Go again y/n? "

  again = gets.chomp != 'n'
end
Sign up to request clarification or add additional context in comments.

7 Comments

Could always loop do ... end and then break if answer.downcase == 'y'
True. But the requirement asks for a Boolean var.
if answer == 'n' would match the requirements more closely.
Could do again = answer == 'n' if that's the case, no need for the if in that case. This is an XY problem, so don't be afraid to get to the root of the issue.
@tadman, nice tip! Updated. PS: it should check for != 'n' to loop again.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.