Home > Mobile >  How to write the code correctly in Ruby? So that it produces the correct output?
How to write the code correctly in Ruby? So that it produces the correct output?

Time:01-21

I want to do something like that.

puts "Please write your age: "
age = gets.chomp

if #{age}<18 
puts "you are illegal"

else #{age}>18
puts "You are legal"
end

the output i get is:

"Please write your age" 15. you are illegal you are legal"

and this

"Please write your age 20 you are illegal you are legal"

Why? And what is the solution please?

What I expect is this If I write 19 or older, it will say "you are legal" And if I write 17 or any number below It will tell me "You are illegal"

CodePudding user response:

Welcome to StackOverflow.

#{} is used for string interpolation, you don't need it there, and else statements don't work like this (elsif does). You also need to convert the string to an integer. You could write it like this:

puts "Please write your age: "
age = gets.chomp.to_i

if age > 18 # Since you want 19 or older. You could use age > 17 or age >= 18 if you actually meant 18 or older.
  puts "You are of legal age"
else
  puts "You are not of legal age"
end

See

CodePudding user response:

The problem is that your code is equivalent to:

puts "Please write your age: "
age = gets.chomp

if 
puts "you are illegal"
else
puts "You are legal"
end

Because # starts a comment, that makes the interpreter ignore everything after it on that line.

You can use any of the suggestions in the other answers to fix the code.

CodePudding user response:

age = gets.chomp.to_i

if age<18

... to get integer-to-integer comparison.

CodePudding user response:

You should first convert the input type to Integer and then make your logic. Note that is also important to check if the string input is numeric (since to_i returns 0 on cases like 'a'.to_i). You can do that like so:

puts 'Please write your age: '
# strip removes leading and trailing whitespaces / newlines / tabs
age = gets.strip

unless age.to_i.to_s == age
  puts 'Age must be a number'
  exit
end

age = age.to_i

if age < 18 
  puts 'you are illegal'
else
  puts 'You are legal'
end
  • Related