Trying to understand application of "gets.chomp"

Hey ya’ll. I learned a bit of javascript and HTML before starting Ruby, and I think that is causing my confusion here. Let’s take the code below:

print “how old are you?”
user_age = Integer(gets.chomp)

if user_age < 40
puts “Not too shabby!”

What confuses me is this. How does Ruby know that gets.chomp is linked to print"how old are you?" It seems that the relation shouldn’t be automatic. After all, we’re not using “div” for instance or using something like "user_age = print “how old are you?”.

I don’t know if I’m explaining this right. It just seems there is a jump in logic. How does Ruby know that ‘gets.chomp’ applies to whatever number is contained in user_age?

gets is short for get string; and, chomp is Ruby for truncate, as in remove the newline character from the end.

It doesn’t, but we do. We wrote it there to prompt the user.

We would never assign a print statement to a variable. The interpreter will throw a syntax error.

It doesn’t. We ask the user for some input, cast it to a number from a string, and if that does not raise a type error, the number is assigned to the variable. It’s our code that told Ruby to do that.

1 Like

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