加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在ruby中有多个构造函数

发布时间:2020-12-17 03:15:59 所属栏目:百科 来源:网络整理
导读:参见英文答案 In Ruby is there a way to overload the initialize constructor?????????????????????????????????????7个 有没有办法在ruby中有多个“初始化”方法? 例如:一个方法除了一个参数而另一个方法除了三个? 就像是 class One def initialize (a
参见英文答案 > In Ruby is there a way to overload the initialize constructor?????????????????????????????????????7个
有没有办法在ruby中有多个“初始化”方法?
例如:一个方法除了一个参数而另一个方法除了三个?

就像是

class One
  def initialize (a)
    puts a
  end
  def initialize_1 (a,b)
    puts a,b 
  end
end

解决方法

initialize实际上不是构造函数.你确实可以有两个构造函数.

class One
  singletonclass.class_eval{alias old_new :new}
  def self.new a
    puts a
    old_new
  end
  def self.new_1 a,b
    puts a,b
    old_new
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读