Mikhail Mikhail -4 years ago 132
Ruby Question

Errors with exclamation marks with methods in Ruby

I get confused why .method! gives you an error whenever it gets nothing to do in the code unlike .method.

Here is an example where I got stuck:

print "Input something that containts 's'."
user_input = gets.chomp.downcase!
if user_input.include? "s"
puts "We got your 's'!"
end


Whenever I .downcase! downcased string or capitalize! capitalized strings and etc. I get an error. When the exclamation point is removed after the .method everything works fine.

Can someone explain to me why this happens?

And why .method! is so popular in Ruby? It looks very discouraging for me to pick .method! over .method because of the issue above.

Answer Source
s = 'ABC'
s.downcase
s # 'ABC'

As you can see s is still ABC because downcase return the string downcased, not modify my object s. So,

s.downcase!
s # 'abc'

permits me to modify my s and I can avoid to do

s = s.downcase

issue is the downcase! method returns nil if no changes are made so your user_input is nil and that's a problem in the next line when you call include? on it. Anyway, you are calling downcase on a temporary object, not on your own object, so you can easily use downcase in this case

user_input = gets.chomp.downcase
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download