Frage

I want to do something like this. Here is one class:

module MyModule
  class ClassOne
    def initialize
      @chain = []
    end

    def add_type_one(thing1, thing2)
      @chain << thing1 + thing2
    end

    def add_type_two(thing3, thing4)
      @chain << thing3 + thing4
    end

    def sanitize
      @chain.join(" ").gsub("this", "that")
    end
  end
 end

Here is another class:

module MyModule
  class ClassTwo
    def initialize
      @other_chain = []
    end

    def add_more(thingA, thingB)
      @other_chain << thingA + thingB
    end

    def add_even_more(thingC, thingD)
      @other_chain << thingC + thingD
    end

    def run
      system('program #{@chain} #{@other_chain}')
    end
  end
 end

Then I'd like to call these methods like so:

a = ClassOne.new
a.add_type_one("I", "Want")
a.add_type_two("These", "Methods")
a.sanitize

b = ClassTwo.new
b.add_more("And", "Variables")
b.add_even_more("To", "Work together")
b.run

What must be done to get a final output of

system('program I Want These MethodsAndVariablesToWork together')

The point of this example is simply that I do not have access to ClassOne methods or variables within ClassTwo. The

 b.run

needs to take in some message or output from ClassOne. I know that instance variables aren't accessible outside of the instance of the class, and I know that I could use a global variable or a constant and that could work - but this is not the best practice. I don't know why this still isn't clear to me. I'm missing a small piece of this puzzle. Please advise.

War es hilfreich?

Lösung

Imagine you had multiple ClassOne instances. How would ClassTwo even know which instance to use?

You could approach this problem by injecting an instance of ClassOne into ClassTwo. Like so

a = ClassOne.new
a.add_type_one("I", "Want")
a.add_type_two("These", "Methods")
a.sanitize

b = ClassTwo.new(a)
b.add_more("And", "Variables")
b.add_even_more("To", "Work together")
b.run

And then access the instance variables of ClassOne from within ClassTwo.

Andere Tipps

Have it in the following way so that the ClassOne is accessible by the ClassTwo,

module MyModule
   class ClassOne
   attr_reader :chain
      def initialize
         @chain = []
      end

      def add_type_one(thing1, thing2)
         @chain << thing1 + thing2
      end

      def add_type_two(thing3, thing4)
         @chain << thing3 + thing4
      end

      def sanitize
         @chain = @chain.join(" ").gsub("this", "that")
      end
   end

   class ClassTwo
      def initialize(obj)
         @classOne = obj
         @other_chain = []
      end

      def add_more(thingA, thingB)
         @other_chain << thingA + thingB
      end

      def add_even_more(thingC, thingD)
         @other_chain << thingC + thingD
      end

      def run
         system('program #{@classOne.chain} #{@other_chain.join}')
      end
   end
end
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top