Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 我该如何避免“不”字;在无效上下文中无用地使用==”;在RSpec?_Ruby_Rspec_Warnings - Fatal编程技术网

Ruby 我该如何避免“不”字;在无效上下文中无用地使用==”;在RSpec?

Ruby 我该如何避免“不”字;在无效上下文中无用地使用==”;在RSpec?,ruby,rspec,warnings,Ruby,Rspec,Warnings,在RSpec中,如果我在 x.should == 42 another_line_of_code 然后我得到一个关于 warning: useless use of == in void context 除此之外,还有什么我能做的吗 关闭警告 将其更改为bitbucket=(x.should==42) RSpec-2有一个eq(预期)匹配器,其工作原理与=一样,没有警告: actual.should eq(expected) 您还可以使用actual.should==expected。这

在RSpec中,如果我在

x.should == 42
another_line_of_code
然后我得到一个关于

warning: useless use of == in void context
除此之外,还有什么我能做的吗

  • 关闭警告
  • 将其更改为
    bitbucket=(x.should==42)
  • RSpec-2有一个
    eq(预期)
    匹配器,其工作原理与
    =
    一样,没有警告:

    actual.should eq(expected) 
    

    您还可以使用
    actual.should==expected
    。这完全取决于你认为什么看起来更漂亮

    使用:

    x.should eq(42)
    
    或:

    或者移动
    x.should==42
    ,使其成为it块中的最后一行


    对于那些想知道为什么的人

    我完全不喜欢Ruby,但我的理解是:

    这个警告来自Ruby,因为像
    x.should==42
    1==1
    这样的语句返回一个值。如果这个返回值没有实际使用(例如,分配给变量、用作函数的参数或从块返回),那么Ruby可以理解地认为首先使用该语句没有任何意义,并提醒您这一点

    要测试这一点,您可以使用-w标志启动irb,并添加以下代码:

    > irb -w
    
    def example
      1 == 1
      :hello
    end
    
    1==1应该发出关于void上下文中无用==的警告。在没有:hello行的情况下尝试,您将不会得到警告,因为
    1==1
    将被用作返回语句


    我知道Op和这里的其他人已经理解了这一点。然而,我想为像我这样的人发布这篇文章,他们可能想知道为什么会发出警告,为什么提出的解决方案解决了这个问题。

    这应该是上下文中公认的答案。
    > irb -w
    
    def example
      1 == 1
      :hello
    end