Why the "!"s ? - 6/7


#1

My code works, you can see a sample below but I was wondering why it forces you to put an “!” after “.capitalize” and “.upcase” because the output seems to work the same without it

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

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

print "What city do you live in?"
city = gets.chomp

print "What country do you live in?"
country = gets.chomp

puts "Your name is #{first_name.capitalize!} #{last_name.capitalize!} and you live in #{city.capitalize!}, #{country.upcase!}"

#2

Examine the following code, and the output that follows…

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}!"

puts "Your name is #{first_name.capitalize!} #{last_name.capitalize!} and you live in #{city.capitalize!}, #{state.upcase!}!"
What's your first name? wee
What's your last name? gillis
What city are you from? fort william
What state or province are you from? ph
Your name is Wee Gillis and you're from Fort william, PH!
Your name is   and you live in , !

Notice that last line? That’s your code’s output when nothing happens to the text.

Explanation

The ! operator tells Ruby to perform the mutation in place. Without that, Ruby creates a copy and performs the mutation on it, and leaves the original as is. We would assign that copy to a new variable. When no mutation occurs on the in place variable, Ruby yields nil, which is why there is no information in the last line above. There was nothing to change.


#3

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