In Ruby is there a way to overload the initialize constructor?

后端 未结 7 1500
死守一世寂寞
死守一世寂寞 2020-11-29 00:58

In Java you can overload constructors:

public Person(String name) {
  this.name = name;
}
public Person(String firstName, String lastName) {
   this(firstNam         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 01:41

    I tend to do

    class Person
      def self.new_using_both_names(first_name, last_name)
        self.new([first_name, last_name].join(" "))
      end
    
      def self.new_using_single_name(single_name)
        self.new(single_name)
      end
    
      def initialize(name)
        @name = name
      end
    end
    

    But I don't know if this is the best approach.

提交回复
热议问题