Can someone please explain this behavior? Why does nil return true when result = true if i but returns false when result = false unless i
def my_all?(pattern = nil)
result = true
my_each do |i|
case pattern
when nil
p result, i
result = false unless i
when Regexp
result = false unless i.to_s.match(pattern)
when Class
result = false unless i.is_a?(pattern)
when String, Numeric
result = false unless i == pattern
end
result = yield(i) if block_given? && pattern.nil?
break if !result
end
result
end
def my_all?(pattern = nil)
result = false
my_each do |i|
case pattern
when nil
p result, i
result = true if i
when Regexp
result = true if i.to_s.match(pattern)
when Class
result = true if i.is_a?(pattern)
when String, Numeric
result = true if i == pattern
end
result = yield(i) if block_given? && pattern.nil?
break if !result
end
result
end
In your second example, once
resultis set totrue, nothing ever sets it to false again. So if the first value yielded frommy_eachis truthy, then themy_all?method will return true.This second example seems like more like an implementation of
any?, rather thanall?. Except it is actually only checking the first element. If the firstiis falsey, then the loop will be broken and it will return false. If the firstiis truthy, then it will be set totrueand nothing will set it back tofalse, and the method will return `true.See these two examples, where the only difference is the values yielded by
my_each:true(first value is truthy)false(first value is falsey)