Ruby - 访问被调用的实例变量 class
Ruby - Access instance variables of called class
我有两个 classes Book::Utils,Table::Utils 并且我从另一个不是父子 classes 调用一个 class。
如果我从 class1 调用 class2 -> 在 class2 中,我们可以访问已经存在的 class1 实例变量吗?
module Table
attr_accessor :account_id
class Utils
def initialize(params)
@account_id = params[:account_id]
end
def calculate
book = Book.new
final_account_id = book.get_account_id
return final_account_id
end
end
end
module Book
class Utils
def get_account_id
# Here I want to access Table's instance variables
# Like @account_id + 20
end
end
end
我正在打电话Table::Utils.new({account_id: 1}).calculate
预期结果:21
我们能做到吗?
您需要传递您需要调用的 class 的实例,然后您可以使用访问器:
module Table
attr_accessor :account_id
class Utils
def initialize(params)
@account_id = params[:account_id]
end
def calculate
book = Book.new
final_account_id = book.get_account_id(self)
return final_account_id
end
end
end
module Book
class Utils
def get_account_id(table)
table.account_id + 20
end
end
end
或者只传递需要的值
module Table
attr_accessor :account_id
class Utils
def initialize(params)
@account_id = params[:account_id]
end
def calculate
book = Book.new
final_account_id = book.get_account_id(account_id)
return final_account_id
end
end
end
module Book
class Utils
def get_account_id(other_id)
other_id + 20
end
end
end
我有两个 classes Book::Utils,Table::Utils 并且我从另一个不是父子 classes 调用一个 class。
如果我从 class1 调用 class2 -> 在 class2 中,我们可以访问已经存在的 class1 实例变量吗?
module Table
attr_accessor :account_id
class Utils
def initialize(params)
@account_id = params[:account_id]
end
def calculate
book = Book.new
final_account_id = book.get_account_id
return final_account_id
end
end
end
module Book
class Utils
def get_account_id
# Here I want to access Table's instance variables
# Like @account_id + 20
end
end
end
我正在打电话Table::Utils.new({account_id: 1}).calculate
预期结果:21
我们能做到吗?
您需要传递您需要调用的 class 的实例,然后您可以使用访问器:
module Table
attr_accessor :account_id
class Utils
def initialize(params)
@account_id = params[:account_id]
end
def calculate
book = Book.new
final_account_id = book.get_account_id(self)
return final_account_id
end
end
end
module Book
class Utils
def get_account_id(table)
table.account_id + 20
end
end
end
或者只传递需要的值
module Table
attr_accessor :account_id
class Utils
def initialize(params)
@account_id = params[:account_id]
end
def calculate
book = Book.new
final_account_id = book.get_account_id(account_id)
return final_account_id
end
end
end
module Book
class Utils
def get_account_id(other_id)
other_id + 20
end
end
end