0

当我将一个引用拉入包的方法放在另一个方法中时,它会离开范围并失败。

这样做的正确方法是什么。我尝试过玩“自我”,但我是新手,但没有成功。

所需的解决方案。不工作。返回错误。

nil:NilClass (NoMethodError) 的未定义方法“accounts”

require 'package that has 'accounts''


class Name

    @sandbox = #working API connection

    def get_account
        @sandbox.accounts do |resp|         #This is where error is
          resp.each do |account|

            if account.name == "John"
                name = account.name
            end

          end
        end
    end


end


new = Name.new
p new.get_account

这可行,但不会创建可重用的方法。

require 'package that has 'accounts''

class Name

    @sandbox = #working API connection


        @sandbox.accounts do |resp|       
          resp.each do |account|    
            if account.name == "John"
                p account.name
            end
          end
        end




end


new = Name.new
4

2 回答 2

1

要理解这一点,您需要了解 Ruby 中单例类的概念。

类 Name 是一个对象本身,并且@sandbox是该对象的一个​​实例变量。

如果你写def self.get_account你可以@sandox在那里使用,但是这个方法不适用于 Name 的实例,例如你应该调用Name.get_account而不是Name.new.get_account。实际上,这为 Name 的单例类添加了一个方法,这就是您可以在那里访问@sandbox 的原因。

要创建可以在 的实例中使用的实例变量Name,您应该在 的initialize方法中这样做Name

于 2019-04-22T12:45:43.327 回答
1
  1. 代码中的错误在于@sandbox 是类的一个属性。该值将在创建类的对象时初始化。在类中编写初始化不会有任何效果。@Maxim 在他的回答中解释了这一点。

  2. 对于第二个代码,当解释器运行代码时,它会执行一次。但是该代码不能多次运行。

代码应该是,

require 'package that has 'accounts''


class Name

    def initialize
      @sandbox = #working API connection
    end

    def get_account
        @sandbox.accounts do |resp|         #This is where error is
          resp.each do |account|

            if account.name == "John"
                name = account.name
            end

          end
        end
    end


end


new = Name.new
p new.get_account
于 2019-04-22T13:54:04.153 回答