Thursday, July 10, 2014

Ruby exclamation mark method

In ruby, we see the methods with name ends with ?, ! Most of us know about the use of method name ends with ?. Ex: is_public? We are expecting the method to return result in boolean value(true/false). In exclamatory methods, usage is something different. See the following examples,
a = "A STRING"
puts a.downcase => a string
puts a => A String


b = "ANOTHER STRING"
puts b.downcase! => another string
puts b => another string
For no match case, gsub will return the actual string without any change in it
puts "ruby on rails".gsub("none","--") => ruby on rails
For no match case, gsub! will return nil
puts "ruby on rails".gsub!("none","--").inspect
People call methods ends with exclamation mark is dangerous to use/careful when using it. The reason is, in some cases it will throw exception instead of false. Ex:
save => return false if save fails
save! => raise an exception if save fails
We have a lot of exclamation mark methods in ruby, start looking on each one with their usage and start using it.
Hope it helps..

No comments:

Post a Comment