Answer: Yes and No.
You can achieve the same result as in other languages ββusing various mechanisms, including: -
- Default Values ββfor Arguments
- Variable argument lists (splat operator)
- Defining an argument as a hash
The actual language syntax does not allow you to define a method twice, even if the arguments are different.
Given the three options above, they can 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"] + " " + args["lastName"] unless args["lastName"].nil? @name = name end end class Person def initialize(*args)
You will often see the second mechanism inside Ruby code, especially in Rails, because it offers the best of both worlds and allows some syntactic sugar to produce beautiful code, in particular, not to attach the hash code in curly braces.
This wikibooks link gives some more evidence.
Steve Weet Oct 18 2018-10-18 11:47
source share