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

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

    The answer is both Yes and No.

    You can achieve the same result as you can in other languages using a variety of mechanisms including:

    • Default values for arguments
    • Variable Argument lists (The splat operator)
    • Defining your argument as a hash

    The actual syntax of the language does not allow you to define a method twice, even if the arguments are different.

    Considering the three options above these could be implemented with your example as follows

    # As written by @Justice
    class Person
      def initialize(name, lastName = nil)
        name = name + " " + lastName unless lastName.nil?
        @name = name
      end
    end
    
    
    class Person
      def initialize(args)
        name = args["name"]
        name = name + " " + args["lastName"] unless args["lastName"].nil?
        @name = name
      end
    end
    
    class Person
      def initialize(*args)
        #Process args (An array)
      end
    end
    

    You will encounter the second mechanism frequently within Ruby code, particularly within Rails as it offers the best of both worlds and allows for some syntactic sugar to produce pretty code, particularly not having to enclose the passed hash within braces.

    This wikibooks link provides some more reading

提交回复
热议问题