-2

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
dili021
  • 58
  • 6
  • 4
    Put your code in question, instead linking to images of it. – Marek Lipka Mar 06 '20 at 09:52
  • the code you link to does not contain >> nil this confuses me. please put the code you want to talk about directly here in the question – bjelli Mar 06 '20 at 09:54
  • What is the purpose of the `if i` and `unless i` conditions? It looks like `i` is always a number (and so always *truthy*). – IMP1 Mar 06 '20 at 09:59
  • @imp1 i is not always a number. You can see one of the items is nil. And that is the whole point of my question which you can read above. – dili021 Mar 07 '20 at 17:47
  • Can I confirm that, for your question, the cases where `pattern` is non-nil are not relevant? It might be easier for people to help if your code was simpler (while still demonstrating the problem you're having). – IMP1 Mar 09 '20 at 09:32
  • @IMP1 Actually, only the `pattern = nil` is relevant, so only when no arguments are provided and the method is checking whether eg. all, none, or any items of an array are true. – dili021 Mar 09 '20 at 10:07

1 Answers1

0

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:

IMP1
  • 280
  • 2
  • 11