Skip to content

Instantly share code, notes, and snippets.

@andywenk
Created February 26, 2013 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andywenk/5038259 to your computer and use it in GitHub Desktop.
Save andywenk/5038259 to your computer and use it in GitHub Desktop.
Sample code to show alias and alias_method is working in Ruby. The related blogpost can be found here: http://goo.gl/4dhVy
#!/usr/bin/env ruby
class NoAlias
def nice_method
puts 'I am the nice method'
end
def even_nicer_method
puts 'I am the even nicer method'
end
end
class AliasMethod
def even_nicer_method
puts 'AliasMethod::even_nicer_method called'
end
alias_method :nice_method, :even_nicer_method
end
class Alias
def even_nicer_method
puts 'Alias::even_nicer_method called'
end
alias :nice_method :even_nicer_method
end
class Mother
def say_name
puts 'I am the Mother'
end
alias :name :say_name
end
class Child < Mother
def say_name
puts 'I am the Child'
end
end
class MotherScope
def say_name
puts 'I am the Mother'
end
def self.my_name
#alias :name :say_name
alias_method :name, :say_name
end
end
class ChildScope < MotherScope
def say_name
puts 'I am the Child'
end
my_name
end
puts 'Example without alias'
NoAlias.new.nice_method
NoAlias.new.even_nicer_method
puts
puts 'Example with usage of alias_method'
AliasMethod.new.nice_method
puts
puts 'Example with the usage of alias'
Alias.new.nice_method
puts
puts 'Example for inheritance'
Child.new.name
puts
puts 'Example for class methods in inheritance (scope!)'
ChildScope.new.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment