public
Last active

  • Download Gist
alias_alt.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
class Some
def initialize(n); @n=n; end
def smth; puts @n; end
end
some1 = Some.new(27); some1.smth #=> prints "27", returns nil
 
class Some
alias :smth_else :smth
def smth; smth_else; puts "overriding original smth method"; end
end
some1.smth
# returns nil, and prints:
# 27
# overriding original smth method
 
class Some
save_smth = instance_method(:smth)
define_method :smth do
save_smth.bind(self).call
puts "whatever"
end
end
some1.smth
# returns nil, prints:
# 27
# overriding original smth method
# whatever
 
# method alias can be still invoked
some1.smth_else #=> prints "27", returns nil
some2 = Some.new(82); some2.smth_else #=> prints "82", returns nil
 
# suggested by Robert Klemme (http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/405189)
class Some; private :smth_else; end
some1.smth_else
# gives:
# NoMethodError: private method `smth_else' called for #<Some:0x92d7c98 @n=27>
class Some
def new_method; smth_else; end
end
some1.new_method #=> 27

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.