rubyif-statementunless

Ruby unless vs if logic


Can someone please explain this behavior? Why does nil return true when result = true if i but returns false when result = false unless i

unless case screenshot

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

if case screenshot

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

Solution

  • In your second example, once result is set to true, nothing ever sets it to false again. So if the first value yielded from my_each is truthy, then the my_all? method will return true.

    This second example seems like more like an implementation of any?, rather than all?. Except it is actually only checking the first element. If the first i is falsey, then the loop will be broken and it will return false. If the first i is truthy, then it will be set to true and nothing will set it back to false, and the method will return `true.

    See these two examples, where the only difference is the values yielded by my_each: