Try in ruby

May 15, 2015

Try method

If you get and user is nil the NoMethodError is occurred.

# user is nil
name = # NoMethodError !!!!1

You had better use try method. You can get name value if user is not nil and if user is nil you can get ‘nil’ instead. The NoMethodError is not occurred.

# user is nil
name = user.try(:name) # return nil. not occurred NoMethodError
# user is not nil
name = user.try(:name) # return name value.

You can set default value if user is nil like this.

name = user.try(:name) || "default name"