Ruby - 调用被调用类的实例变量

时间:2018-03-15 12:11:15

标签: ruby class inheritance instance-variables

我有两个类Book :: Utils,Table :: Utils,我从另一个类中调用一个不是父子类的类。

如果我从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 我们可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您需要传递需要调用的类的实例,然后才能使用访问器:

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