-2

有人可以解释这种行为吗?为什么 nil 什么时候返回真,什么时候result = true if i 返回假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
4

1 回答 1

0

在您的第二个示例中,一旦result设置为true,则不会再将其设置为 false 。因此,如果产生的第一个值my_each是真值,那么该my_all?方法将返回真值。

第二个示例看起来更像是 的实现any?,而不是all?. 除了它实际上只检查第一个元素。如果第一个i是假的,那么循环将被打破并返回假。如果第一个i是真值,那么它将被设置为true并且没有任何东西将它设置回false,并且该方法将返回`true。

请参阅这两个示例,其中唯一的区别是由 产生的值my_each

于 2020-03-09T09:30:36.787 回答