user3525734
user3525734

Reputation: 43

How does Ruby know the variable belongs to this code?

I want to know how Ruby knows which variable is assigned to certain codes. For example in this code:

print "What's your first name?"
first_name = gets.chomp
first_name.capitalize!

print "What's your last name?"
last_name = gets.chomp
last_name.capitalize!

print "What city are you from?"
city = gets.chomp
city.capitalize!

print "What state or province are you from?"
state = gets.chomp
state.upcase!

puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}!"

How does Ruby know that the city variable is the answer of the users input from the question "What city are you from?"?

Upvotes: 0

Views: 79

Answers (1)

Sigi
Sigi

Reputation: 1864

The gets method reads a line from standard input, and returns that as a string. chomp is then called on the result of gets (the string that it just read). The result is then assigned to a variable (city, state, etc.).

The method capitalize! actually modifies the object that it is called on. After city.capitalize!, the string referred to by city has been modified (capitalized). This is different from returning a modified version of an object (which is what happens during gets.chomp, where the result of gets never gets stored anywhere, it is immediately modified by chomp and the result of that is then stored).

To further clarify: every call to gets reads a new string from the console, which is then chomped and stored in a variable. This is why your program asks for several inputs and keeps them all around in those variables.

Upvotes: 1

Related Questions