简体   繁体   English

如何初始化Ruby中当前类以外的实例?

[英]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) . 例如,我想对Hello.new(true)Hello.new(false)有不同的行为。 Be precise, I want them to create instance of different classes . 确切地说,我希望他们创建不同类的实例

How could I achieve that in Ruby? 我怎么能在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). 你所说的是Factory模式(至少是一个简单的版本)。 It's possible to split the new process invoking allocate and initialize manually, but I don't recommend it. 可以将new进程拆分为手动allocateinitialize ,但我不推荐它。

The main reason is because it totally counter-intuitive. 主要原因是因为它完全违反直觉。 You'll (almost) never find a Ruby library behaving like this. 你(几乎)永远不会发现Ruby库表现得像这样。

Instead, I suggest you to use a different method. 相反,我建议你使用不同的方法。 For example, #factory . 例如, #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(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 ruby 中动态初始化实例变量? - How to initialise an instance variable dynamically in ruby? ruby - 返回当前类的实例 - ruby - return an instance of current class 如何在Rails服务器启动的ruby类中初始化方法 - How to initialise a method in a ruby class on rails server start up Ruby:定义一个 class,它在没有任何方法调用实例时返回除自身之外的其他内容 - Ruby: define a class that returns something other than itself when an instance is called without any methods 我如何将一个类的实例变量访问到另一个类中的ruby中的其他文件中定义 - how do i access instance variable of one class into other class define in other file in ruby 红宝石:如何获取在当前类而不是基类中定义或覆盖的所有方法? - ruby: how to get all the methods that are defined or overwrited in current class rather than base class? 如何在Ruby中获取当前的实例模块 - How to get the current instance module in Ruby 如何将 Ruby class 实例变量初始化为另一个 class 的新实例? - How to initialize Ruby class instance variable to a new instance of another class? 如何初始化三维ruby数组 - How to initialise a three dimensional ruby array 如何在 Ruby 中单行初始化多个数组? - How to initialise multiple array in single line in Ruby?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM