This is a personal memo.
About the role of & .
. Add &
before the dot in the process of executing the method on a normal object (receiver).
ยท Receiver & .method
** Returns nil instead of error if the receiver is nil **.
Normal processing (error)
x = nil
x.length
=> NoMethodError (undefined method `length' for nil:NilClass)
&.Method
x = nil
x&.length
=> nil
It can return nil without error.
The to_s
method that converts to a string and the to_i
method that converts to a number will default to the default value instead of an error if there is no receiver.
However, using & .
returns nil
when the receiver is nil
.
Normal
x = nil
x.to_s
=> ""
x.to_i
=> 0
&.
x = nil
x&.to_s
=> nil
x&.to_i
=> nil
On a practical basis, if the receiver could be nil, it returns nil instead of an error display, in which case||
Returns the value set by default in.
Example 1
x =nil
x&.lenght || 0
=> 0
Example 1
x =nil
x&.lenght || "is nil"
=> "is nil"
You can simply write like exception handling.
Recommended Posts