When the variable is nil
, some methods may cause an error.
For example, if nil
is included when turning an array with values packed in an array by some processing, the processing will stop and an error will occur. .. It would be a problem if something happened.
In such a case, you can avoid nil
by doingnext if [variable] .nil?
With ** guard clause ** (implemented to remove the exception at the beginning of the function or iteration). I do, but I would like to make a note of it when there is another method that applies logical operators.
First of all, from the conclusion, write in the form of [object] &. [Method]
.
For example
# Without &
ary = [[1,2,3],nil,[5,6]]
ary.each do |element_ary|
p element_ary.length
end
=>
3
Traceback (most recent call last):
2: from test.rb:3:in `<main>'
1: from test.rb:3:in `each'
test.rb:4:in `block in <main>': undefined method `length' for #nil:NilClass (NoMethodError)
# With &
ary = [[1,2,3],nil,[5,6]]
ary.each do |element_ary|
puts element_ary&.length
end
=>
3
nil
2
In this way, there are no errors.
Actually, this involves the logical operator &&
.
In general, logical operators have the following characteristics:
・ Evaluated in order from the left ・ Once the truth of a logical expression is determined, the remaining expressions are not evaluated. -The value of the last evaluated expression becomes the value of the entire logic.
That is, when [Condition 1] && [Condition 2]
is found, [Condition 2]
is evaluated only when [Condition 1]
is true. This is because if [condition 1]
is nil
or false
, the result of the logical operator &&
is nil
or false
without evaluating condition 2.
Applying this and explaining using the above example, it can be written as follows.
ary = [[1,2,3],nil,[5,6]]
ary.each do |element_ary|
p element_ary && element_ary.length
end
When nil
is entered in ʻelement_ary, the processing of the logical operator ends at
[condition 1] and returns
nil, so
nil is added to the
lengthmethod of
[condition 2]`. Will not cross.
It was called a safety reference operator that could be expressed by omitting this and adding &
after the object as shown below.
ary = [[1,2,3],nil,[5,6]]
ary.each do |element_ary|
p element_ary&.length
end
It was an application example of logical operators, but I thought it was nice.
Recommended Posts