+ 8

Is method over riding and over loading using in Ruby.

In java these methods are used...is it possible for ruby?

15th Jul 2017, 9:05 AM
Hashan Malawana
Hashan Malawana - avatar
7 Antworten
+ 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
17th Jul 2017, 10:20 AM
Pao
Pao - avatar
+ 3
thanks in advance..
17th Jul 2017, 11:20 AM
Hashan Malawana
Hashan Malawana - avatar
+ 1
Usefull
7th Aug 2017, 7:14 AM
Thilina Jayawardana
Thilina Jayawardana - avatar
+ 1
Nice
7th Aug 2017, 7:26 AM
amith weerasinghe
amith weerasinghe - avatar
+ 1
Thanks
7th Aug 2017, 7:26 AM
amith weerasinghe
amith weerasinghe - avatar
+ 1
great
7th Aug 2017, 7:36 AM
Chamith Sandagiri
+ 1
work
7th Aug 2017, 7:37 AM
Chamith Sandagiri