【问题标题】:Ruby NameError: undefined local variable or method `r' forRuby NameError:未定义的局部变量或方法“r”
【发布时间】:2015-07-22 00:02:35
【问题描述】:

我在某个类中有这段代码,顺便说一句,这是带有测试/单元的普通 ruby​​,不涉及 Rails:

 10  %w[["y",true],["n",false]].each do |r, state|  
 11   def must_continue_to_ask_for_input_until_given_yes_or_no
 12
 13     provide_input(r)
 14 
 15     assert_equal state, @questioner.ask(@question)
 16   end
 17 end

vim 编辑器中使用 !ruby % 运行它时,我收到此错误:

  Line 13, NameError: undefined local variable or method `r' for #<QuestionerTest:0x007fe931981fd0>

QuestionerTest 是我的类,它派生自

Class QuestionerTest <Test::Unit::TestCase

环境:

Ruby 2.2.1 on MACOSX Mavericks
No rails involved
test/unit involved

【问题讨论】:

    标签: ruby macos exception nameerror


    【解决方案1】:

    这是因为当你定义一个这样的方法时,你每次都在重写,而且,每次它的定义都是一样的。这是因为“def 方法”就像一个延迟执行——当它被调用时,ruby 方法不会“看到” r 和 state 在范围内。

    另外,"%w" 构造期望将一系列字符串转换为数组,所以可能不是你想的那样:

    %w[one two three] == ["one", "two", "three"]
    
    %w[["y",true],["n",false]].first
      => "[\"y\",true],[\"n\",false]"
    
    %w[["y",true],["n",false]].first.class
      => String
    

    如果你想在捕获周围的变量的同时生成多个方法,你可以这样做:

    irb(main):043:0> [1,2,3].each do |r|
    irb(main):044:1* define_method(:"foo#{r}") { |a| puts a, r }
    irb(main):045:1> end
    => [1, 2, 3]
    
    irb(main):046:0> foo1("hi")
    hi
    1
    => nil
    
    irb(main):047:0> foo2("bye")
    bye
    2
    => nil
    

    【讨论】:

      【解决方案2】:

      首先,我要感谢 adzdavies 抽出时间回答我的愚蠢问题。现在根据他的回答,这是我为修复它而编写的代码:

      def must_continue_to_ask_for_input_until_given_yes_or_no
       [["y",true],["n",false]].each do |r, state|  
        %w[Note Yesterday axyesq].each do |mu|
          expect_output @question
          provide_input(mu)
          expect_output("I don't understand")
        end
        expect_output @question
        provide_input(r)
      
        assert_equal state, @questioner.ask(@question)
      end
      

      结束

      再次感谢,让我们 Ruby!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-19
        • 1970-01-01
        • 2016-02-14
        • 2016-04-08
        相关资源
        最近更新 更多