Why the "!"s ? - 6/7


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


Examine the following code, and the output that follows…

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

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

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

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

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.


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.


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