Frage

I'm porting some code from other language to Ruby, in my Class I need to maintain compatibility with those 4 constructors:

def initialize(b)
def initialize(a, b)
def initialize(b, c)
def initialize(a, b, c)

I was trying this way but it does not work:

def initialize(a="", b, c="")

Is there a smart solution? I cannot use hash.

War es hilfreich?

Lösung 3

This could be a solution, but well it's ugly!

def initialize(*args)
    case (args.length)
        when 1
            super(XXX)
            @y = args[0]
        when 2
            if args[0].kind_of?(A) then
                super(args[0])
                @x = args[0]
                @y = args[1]
            elsif args[0].kind_of?(B) then
                super(XXX)
                @y = args[0]
                @z = args[1]
            end 
        when 3
            super(args[0])
            @x = args[0] 
            @y = args[1]
            @z = args[2]
    end
end

Andere Tipps

If you can't use a hash (why not?), and they must be initialize methods, you're likely out of luck. Without typing or positional information, there's just no way to destructure, say, an array, and determine which argument is which.

IMO the cleanest would be to provide class methods that do the construction and accept the arguments specific to the constructor (factory, in this case).

If the arguments are of different types you could use that information to determine which values are being passed in, I suppose, but IMO that gets pretty ugly pretty fast.

If a,b,c are completely different types, and always will be, then perhaps something like this:

def initialize(*args)
   args.each do |arg| 
      do_a if arg.is_a?(first_type)
      do_b if arg.is_a?(second_type)
      do_c if arg.is_a?(third_type)
   end
end

I'll admit, it is not pretty but it should work. If you are only wanting 3 params then limit the each to only run 3.times.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top