当将引用的打包方法放入对象方法中时,该方法会超出范围 [英] Method referring to a pulled in packaged's method moves out of scope when put inside an objects method
问题描述
当我在另一个方法中放置一个引用引入包的方法时,它将离开作用域并失败.
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 'self' but am new and that did not work out.
所需的解决方案.不起作用.返回错误.
Desired solution. Does not work. Returns error.
nil:NilClass的未定义方法帐户"(NoMethodError)
undefined method `accounts' for nil:NilClass (NoMethodError)
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
这有效,但不会创建可重用的方法.
This works but does not create a reusable method.
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
推荐答案
-
代码中的错误是@sandbox是类的属性.创建类的对象时,将初始化该值.在类中编写初始化将无效. @Maxim在回答中对此进行了解释.
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.
对于第二个代码,当解释器运行该代码时,它将执行一次.但是该代码不能运行多次.
For the second code, when the interpreter runs through the code, it would execute it once. But that code cannot run more than once.
代码应为
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
这篇关于当将引用的打包方法放入对象方法中时,该方法会超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!