Search code examples
rubyclassinheritanceinstance-variables

Ruby - Access instance variables of called class


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?


Solution

  • 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