If statements and 'gets.chomp'-variables


#1



Link to exercise (it's a review lesson where i should make something i wanted)
https://www.codecademy.com/en/courses/ruby-beginner-en-NFCZ7/3/1?curriculum_id=5059f8619189a5000201fbcb

I'm not exactly sure, can i, as i have done in the code, set a variable to 'gets.chomp' and then use it in an if-elsif-else statement. Please tell me if there is something wrong with my code:


print "Type an integer and the program will configure out wether it is positive, negative, or just 0:"

variable = gets.chomp

if variable > 0
    print "Your number is a positive integer"
elsif varible < 0
    print "Your number is a negative integer"
else
    print "Your number is 0"
end

It also outputs this error message:
comparison of String with 0 failed

I don't understand that error message. Can you help me?


#2

Check typo in elsif clause.

gets take an user input and saves as a string, You need to convert it in number.
use .to_i or Integer().


#3

Could you show me exactly how the syntax is (how to do and where to put it)?


#4

We learnt that we can chain our methods , right ?

It can be like this..

gets.chomp.Method_I_mentioned ( to_i)

or you can use Integer() over your input.


#5

I don't encourage it's use but in Ruby you can use the global variable $_ to store the last gets

Example

case $_.downcase.chomp

if X then Y
end
if foo then bar
end
etc etc etc


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.