Method referring to a pulled in packaged's method moves out of scope when put inside an objects method

后端 未结 2 417
抹茶落季
抹茶落季 2021-01-26 09:31

When I put a method that refers to a pulled in package inside another method it leaves scope and fails.

What is the proper way to do this. I tried playing with the \'se

相关标签:
2条回答
  • 2021-01-26 10:07
    1. The mistake in the code is that @sandbox is an attribute of the class. The value would be initialized when an object of the class is created. Writing the initialization in the class will have no effect. @Maxim has explained this in his answer.

    2. For the second code, when the interpreter runs through the code, it would execute it once. But that code cannot run more than once.

    The code should be,

    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
    
    0 讨论(0)
  • 2021-01-26 10:21

    To understand this, you need to understand the concept of singleton classes in Ruby.

    The class Name is an object itself, and @sandbox is an instance variable of that object.

    If you write def self.get_account you could use @sandox there, but then this method is not available for instances of Name, e.g. you should call Name.get_account and not Name.new.get_account. Actually, this adds a method to the singleton class of Name, and that's why you can access @sandbox there.

    To create an instance variable that could be used in the instances of Name, you should do so in the initialize method of Name.

    0 讨论(0)
提交回复
热议问题