0

I have this loop:

puts "Welcome to the Loop Practice Problems"
puts " Write a number between 1 and 10, but not 5 or else...."
ans = gets.chomp!
if ans < 1
  puts "Tf bruh bruh"
elsif ans > 10
  puts "Now you just playin"
elsif x == 5
  print "You wildin B"
else
  puts "Fosho that's all I require"
end

It doesn't run properly, and I'm trying to understand why. If you can help me with this, I'd appreciate it.

If you know a good site for practice problems, I'd love to try it. I checked out Coderbyte and Code Kata, but the way they're set up doesn't look right, and they don't have questions to solve for fundamentals.

5
  • 1
    You also have a typo in elsif x==5 should be elsif ans==5 Commented Apr 27, 2018 at 0:34
  • 4
    You don't have a loop. Commented Apr 27, 2018 at 3:47
  • 2
    Define what you mean by "run properly". Commented Apr 27, 2018 at 3:48
  • Is there any significance in using print just under the third branch? Commented Apr 27, 2018 at 3:49
  • You can start practicing ruby: codecademy.com/courses/learn-ruby/lessons Commented Apr 27, 2018 at 3:52

2 Answers 2

3

The issue here is that you're not converting ans to a number, but you're comparing it to one. ans is going to be a string.

In Ruby, when you compare a number to a string, Ruby says that the two aren't equal:

"1" == 1
=> false

You can reproduce the problem with this code:

puts "Welcome to the Loop Practice Problems"
puts " Write a number between 1 and 10, but not 5 or else...."

ans=gets.chomp!
p ans

The p method will output an "inspected" version of that object, (it's the same as doing puts ans.inspect). This will show it wrapped in quotes, which indicates that it's a string.

You probably want to do this:

ans = gets.chomp!.to_i

The to_i method here will convert the number to an integer, and then your comparisons will work correctly.

Sign up to request clarification or add additional context in comments.

2 Comments

And you probably want chomp (without !) since the bang variant might return nil.
@Stefan you probably do not want chomp at all, since "1\n".to_i #⇒ 1 :)
0

You have to convert input string type object into integer type

ans = gets.chomp!.to_i #input string convert into integer.
if ans < 1
  puts "Tf bruh bruh"
elsif ans > 10
  puts "Now you just playin"
elsif x == 5
  print "You wildin B"
else
  puts "Fosho that's all I require"
end

Comments

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.