I was just trying to explore oops concept in ruby
inheritance using mixins
overloading(not exactly) as var arg passing
i just wanted to what do we call this in OOPS terms
class Box
def method1(str)
puts "in old method 1"
end
def method1(str)
puts "in new method 1"
end
end
# create an object
box = Box.new
box.method1("asd")
this is my ruby class , obviously the one defined second gets executed , but I am looking for any expert comprehension from SO over this
class Box
def method1(str="")
puts "in old method 1"
end
end
Pass default value
Overloading means a class may have same method name with either different number parameter or different parameter types. Ref overloading
This is the case in most of the programming language, but in Ruby overloading doesn't exist
as ruby is more concerned on the method calling on the parameters instead of the type of parameters. Ref Duck Typing
for ex:-
def add(a, b)
a + b
end
# Above method will work for the each of the following
# add(2, 3)
# add("string1", "string2")
# add([1,2,3], [4,5,6])
So, One must wondering how we will achieve Overloading in Ruby, and answer would be
def some_method(param1, param2 = nil)
#Some code here
end
# We can call above method as
# 1. some_method(1)
# 2. some_method(1, 2)
OR
def some_method(param1, param2 = nil, param3 = nil)
#Some code here
end
# We can call above method as
# 1. some_method(1)
# 2. some_method(1, 2)
# 3. some_method(1, 2, 3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.