2

How can I get this Java-like effect in Ruby?

class Outer {
  final boolean switch
  public Outer(boolean someSwitch) {
   switch = someSwitch
  }

  class Inner {
    public void doSomething() {
      if (switch) {
        //behave like this
      } else {
        //behave like that
    }
  }
}

Never mind that the switch has to be final; in Scala, it doesn't. Anyway. My Inner class lives within the scope of an Outer instance, and that is how I like it. And I don't have to pass the switch to each individual inner instance.

In Ruby, I can nested a class inside another, but it doesn't mean anything beyond a namespace. How can I get the effect that I want? I know the question is a little vague, so feel free to take a stab at it even if you're not sure.

Ladlestein
  • 6,100
  • 2
  • 37
  • 49

1 Answers1

4

There are no nested classes in Ruby, more info here. But Ruby being awesome as it is you can do this if it helps.

module M
  class Outer
    attr_accessor :foo

    def say_hello()
      puts "Hello Outer '#{@foo}'"
      Inner.new(self).say_hello()
    end

    private

    class Inner

      def initialize(parent)
        @parent = parent
      end
      def say_hello()
        puts "Hello Inner '#{@parent.foo}'"
      end
    end
  end
end


instance = M::Outer.new
instance.foo = "foo values"
instance.say_hello

#=> Hello Outer 'foo values'
#=> Hello Inner 'foo values'
Community
  • 1
  • 1
Haris Krajina
  • 14,824
  • 12
  • 64
  • 81
  • What I'd like to avoid is having to pass the 'parent' argument to the inner class, and having to keep another instance variable in the inner class to hold the reference to the parent. My little inner class has enough parameters in its initialize method and enough instance variables already. – Ladlestein Nov 16 '12 at 18:56
  • I know, but I think you are stuck with few approach I left in link above. In my opinion this is the cleans maybe some other will be more up to you liking. – Haris Krajina Nov 18 '12 at 18:10