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

后端 未结 7 1528
死守一世寂寞
死守一世寂寞 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:22

    You can use konstructor gem to declare multiple constructors in Ruby and imitate overloading:

    class Person
      def initialize(name)
        @name = name
      end
    
      konstructor
      def from_two_names(first_name, last_name)
        @name = first_name + ' ' + last_name
      end
    end
    
    Person.new('John Doe')
    Person.from_two_names('John', 'Doe')
    

提交回复
热议问题