+ 8
Is method over riding and over loading using in Ruby.
In java these methods are used...is it possible for ruby?
7 odpowiedzi
+ 5
[ OVERLOADING ]
Technically it can't be achieved the way it's done in Java (because Ruby is a dynamic typed lang), the latter method will be called if we call 2
methods with the same name. But, Ruby supports different ways to achieve this:
■ Using Optional Parameters:
def method(*args)
if args.length == 1
#method 1
else
#method 2
end
end
■ Using Hash:
def method(options)
if options[:arg1] and options[:arg2]
#method 2
elsif options[:arg1]
#method 1
end
end
method arg1: 'solo', arg2: 'learn'
■ The third-party library called "contracts.ruby" also allows overloading.
[ OVERRIDING ]
You can find detailed info here: http://rubylearning.com/satishtalim/ruby_overriding_methods.html but basically it can be done by:
■ Invoking 'super'
class Bicycle
attr_reader :gears, :seats
def initialize(gears = 1)
@seats = 1
@gears = gears
end
end
class Tandem < Bicycle
def initialize(gears)
super
@seats = 2
end
end
b = Bicycle.new
puts b.gears # outputs 1
puts b.seats # outputs 1
t = Tandem.new(2)
puts t.gears # outputs 2
puts t.seats # outputs 2
+ 3
thanks in advance..
+ 1
Usefull
+ 1
Nice
+ 1
Thanks
+ 1
great
+ 1
work