user.try(:[],:name)
The first time I saw this code "Why are you putting an empty array in the method part ...?" I thought. It's a bad thing that I skipped the Ruby (Rails) grammar ...
Methods included in Active Support (cannot be used only in Ruby) Use the specified method only when the target object is not nil Give the method you want to use as the first argument and its argument (if necessary) as the second argument
user = {name: "test"}
# user[:group]Causes a method error because is nil
user[:group].replace("A")
# => NoMethodError: undefined method 'replace' for nil:NilClass
#If you use try on a nil object, no error will occur, only nil will be returned.
user[:group].try(:replace,"A")
=> nil
That's the main subject, but ruby's Hash has a [] method. Takes the key name as an argument and returns its value.
user.[] :name
=> "test"
#This is user[:name]Same as
By the way, "+" etc. can also be used as a method.
user[:name].+ 2
=> "test2"
In this case, it's a combination of try and this method.
user.try(:[],:name)
=> "test"
The result will be returned.
It was a little difficult to understand because I didn't hit [] easily. Re-study ruby / rails grammar ...
Recommended Posts