为什么在case语句中ruby类比较失败?

sh7euo9m  于 2023-06-22  发布在  Ruby
关注(0)|答案(1)|浏览(89)

在下面的rspec示例中,为什么when Question不正确?

require "rails_helper"
class Question
end

describe Question do
  it "confuses me" do
    klass = Question

    # this passes
    expect(klass).to eq(Question)

    # this doesn't fail (thankfully)
    fail "loudly" if klass != Question

    case klass
    when Question # this doesn't match 🤔???
      tada = "🎉"
      expect(tada).to eq("🎉")
    else
      # why?????
      fail "into confusion"
    end
  end
end

不,这不是一个课程作业,哈哈。我在工作中遇到了这个现在我不知道什么是真的了。
边注,使用字符串比较工作:

require "rails_helper"
class Question
end

describe Question do
  it "confuses me" do
    klass = Question

    # this passes
    expect(klass).to eq(Question)

    # this doesn't fail (thankfully)
    fail "loudly" if klass != Question

    case klass.to_s
    when Question.to_s # this doesn't match 🤔???
      tada = "🎉"
      expect(tada).to eq("🎉")
    else
      # why?????
      fail "into confusion"
    end
  end
end

另一方面:使用rspec是测试这种意外行为的方便方法。这个问题与rspec无关。

xytpbqjk

xytpbqjk1#

我刚刚了解到,如果我想比较两个类,它们都需要实现===。下面是一个工作示例:

require "rails_helper"
class Question
  def ===(other)
    other == self
  end
end

describe Question do
  it "confuses me" do
    klass = Question

    # this passes
    expect(klass).to eq(Question)

    # this doesn't fail (thankfully)
    fail "loudly" if klass != Question

    case klass.to_s
    when Question.to_s # this doesn't match 🤔???
      tada = "🎉"
      expect(tada).to eq("🎉")
    else
      # why?????
      fail "into confusion"
    end
  end
end

这篇文章帮助我找到了答案:https://thoughtbot.com/blog/case-equality-operator-in-ruby

相关问题