简体   繁体   中英

How to initialise an instance other than the current class in Ruby?

I want to initialize instances of different class based on the initial params. For example, I want to have different behavior for Hello.new(true) and Hello.new(false) . Be precise, I want them to create instance of different classes .

How could I achieve that in Ruby?

class Name1
end

class Name2
end

class Hello
  def initialize(opts)
    if opts
      Name1.new
    else
      Name2.new
    end
  end
end

What you are talking about is called Factory pattern (at least, a simple version). It's possible to split the new process invoking allocate and initialize manually, but I don't recommend it.

The main reason is because it totally counter-intuitive. You'll (almost) never find a Ruby library behaving like this.

Instead, I suggest you to use a different method. For example, #factory .

class Name1
end

class Name2
end

class Hello
  def self.factory(opts)
    klass = if opts
      Name1
    else
      Name2
    end
    klass.new
  end
end

Hello.factory(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM