0

I have two classes Book::Utils, Table::Utils and I calling one class from the other which are not parent-child classes.

If I call class2 from class1 -> In class2, can we access already present class1 instance variables?

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

I am calling Table::Utils.new({account_id: 1}).calculate

Expected result : 21 Can we achieve this?

1 Answer 1

1

You need to pass instance of the class you need to call and then you can use accessors:

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

or just pass the value that is needed

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
Sign up to request clarification or add additional context in comments.

3 Comments

For 1 instance variable the solution is known. But its for many instance variables( params > 10)
What do you mean many instance variables? Just pass a class instance and then use accessors.
Ur first solution works i.e., book.get_account_id(self). Ideally I should pass more than 1 param in this. Ex: get_account_id(@account_id, @user_id, @sync_id......etc). Passing self solves the problem. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.