Search code examples
rubyclassinstance

Talking to a Ruby class’ instance of another class


This has probably been answered before, but I lack the proper vocabulary to find the solution using the board search.

What I want to achieve is to calling methods of a class’ instance of another class.

I think this crude example illustrates what I want to achieve:

class ClassA
  def method_a
    return 'first example'
  end

  def method_b
    return 'second example'
  end
end

class ClassB
  def initialize
    object = classA.new
  end
end

the_example = classB.new
the_example.[whatever-I’m-missing-to-talk-with-object].method_b 
# should return 'second exampe'

Solution

  • object needs to be an instance variable so that it doesn't go out of scope after the call to initialize, so call it @object instead.

    Then you'll need to make @object accessible outside of classB's definition, so you'll want to declare that.

    class ClassB
      attr_reader :object # lets you call 'some_instance_of_classb.object'
      def initialize
        @object = ClassA.new
      end
    end