I saw a sample code of Ruby where in a class can have two methods with
the same name and same set of parameters:
For example:
class method_versions
def method
puts "first"
end
def method
puts "second"
end
end
On executing: method_versions.new.method
it returns: second
Just in case I want to return the older version of the method, what
could be done?
on 2012-08-16 18:06
on 2012-08-16 18:54
On Thu, Aug 16, 2012 at 11:06 AM, Rubyist Rohit <lists@ruby-forum.com> wrote: > def method > puts "second" > end > end > > On executing: method_versions.new.method > it returns: second > > Just in case I want to return the older version of the method, what > could be done? Any time a method is defined, it overrides any previous definition of a method by that name (regardless of the argument list of either definition). The only way to access the previous definition is to first save it in an alias: class Method_versions def method puts "first" end alias :old_method method def method puts "second" end end mv = Method_versions.new mv.old_method mv.method
on 2012-08-16 18:55
So this means there is no versioning but overriding of the previous one. Alias is nothing but a different name given to a method.
on 2012-08-16 20:51
On Thu, Aug 16, 2012 at 11:55 AM, Rubyist Rohit <lists@ruby-forum.com>
wrote:
> So this means there is no versioning but overriding of the previous one.
Right.
on 2012-08-19 08:17
On Thu, Aug 16, 2012 at 11:06 AM, Rubyist Rohit <lists@ruby-forum.com>wrote: > def method > -- > Posted via http://www.ruby-forum.com/. > > Subclass it, then override it. If you want to call the original, invoke `super` class C def m 'the original' end end class C2 < C def m "I override #{super}" end end C2.new.m # => "I override the original"
Please log in before posting. Registration is free and takes only a minute.
Existing account
(Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
Log in with Google account | Log in with Yahoo account
No account? Register here.