Skip to content

Instantly share code, notes, and snippets.

@rentalcustard
Created August 6, 2013 14:54
Show Gist options
  • Save rentalcustard/6165204 to your computer and use it in GitHub Desktop.
Save rentalcustard/6165204 to your computer and use it in GitHub Desktop.
#if I have...
A.new(B.new(C.new(D.new)))
#is there some way (some inject sorcery?) to construct this from a list of the classes?
list = [A, B, C, D]
@dbussink
Copy link

dbussink commented Aug 6, 2013

Maybe something like this?

def recursive_new(list)
  cls = list.shift
  cls.new(recursive_new(list)) if cls
end

@fronx
Copy link

fronx commented Aug 6, 2013

class X
  def initialize(other)
    @other = other
  end
end

class A < X; end
class B < X; end
class C < X; end
class D < X; end

[ A, B, C, D ].reverse.inject { |acc, klass| klass.new(acc) }

@rentalcustard
Copy link
Author

I finally settled on

[A, B, C].reverse.inject(D.new) {|acc, klass| klass.new(acc) }

Which is obviously cheating, but whatever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment