ruby 在case语句与if语句中比较类时出现意外结果

gwo2fgha  于 2023-04-20  发布在  Ruby
关注(0)|答案(2)|浏览(102)

所以我写了一个模块函数来将'falsey'和'truthy'值转换为true和false。为了做到这一点,我使用了一个case表达式,据我所知,它基本上就是a big elseif statement that uses the === function,其中的===操作符用于比较集合。从Ruby documentation中,我能真正找到的==和===之间的唯一区别是==========================================================================================================================================================我也理解everything is a method call in ruby,所以我们不能假设等式/包容方法是可交换的。
当使用case语句按类排序时,我会猜测==和===的功能是相同的,但我发现当按类排序时,case语句从未将我的输入放入正确的“bin”中。在这一点上,我切换到使用==,它确实工作,所以我想知道为什么会这样,因为我正在比较我假设实际上是一个“”的类。苹果与苹果的比较

module FirstTry
  def self.to_boolean(uncertain_value, to_integer: false)
    case uncertain_value.class
    when String
      value = ActiveRecord::Type::Boolean.new.cast(uncertain_value)
      return 1 if to_integer == true && value == true
      return 0 if to_integer == true && value == false
      return boolean_value
    when TrueClass
      return 1 if to_integer == true
      return true
    when FalseClass
      return 0 if to_integer == true
      return false
    when NilClass
      return 0 if to_integer == true
      return false
    end
    # I did not originally include this part of the code in the question
    raise 'Conversion Failed: No rules for converting that type of input into a boolean.'
  end
end

module SecondTry
  def self.to_boolean(uncertain_value, to_integer: false)
    if uncertain_value.class == String
      boolean_value = ActiveRecord::Type::Boolean.new.cast(uncertain_value)
      return 1 if to_integer == true && boolean_value == true
      return 0 if to_integer == true && boolean_value == false
      return boolean_value
    elsif uncertain_value.class == TrueClass
      return 1 if to_integer == true
      return true
    elsif uncertain_value.class == FalseClass
      return 0 if to_integer == true
      return false
    elsif uncertain_value.class == NilClass
      return 0 if to_integer == true
      return false
    end
    # I did not originally include this part of the code in the question
    raise 'Conversion Failed: No rules for converting that type of input into a boolean.'
  end
end
eh57zj3b

eh57zj3b1#

三元组equals ===在Ruby中的case表达式中被调用。我们发现可以方便地表达如下内容:

case object
when String
  "object is an instance of String!"
when Enumerable
  "wow, object is actually a bunch of objects!"
end

当然,这很方便,除非你实际上持有的是类,而不是类的示例。但在你的例子中,你在case表达式中对对象调用了#class。只需删除该调用,你的case就会被放入正确的bin中。:)

baubqpgj

baubqpgj2#

可以在case语句中使用.class.to_s进行比较

相关问题