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..

Tuesday, July 8, 2014

Rails try method name in object

In rails, most cases we are using the following style of code to display name, text etc..
user && user.name
It will go lengthier & is hard to maintain, check the below one
user && !user.comments.blank? && user.comments.first.text
Avoid lengthy expressions, start using "try"
user.try(:name)
It will return user name only if user object exists. Happy coding..