Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Fundamental - Alias para métodos em Ruby
names = ["Akira", "Fernando", "Jose"]
names.length # => 3
names.size # => 3
class MyClass1
def do_something
"Doing..."
end
alias_method :make_something, :do_something
end
m1 = MyClass1.new
m1.do_something # => "Doing..."
m1.make_something # => "Doing..."
class MyClass2
def do_something
"Doing..."
end
alias_method :do_something_original, :do_something
def do_something
"#{do_something_original} And doing more here..."
end
end
m2 = MyClass2.new
m2.do_something # => "Doing... And doing more here..."
# You didn't write this code
class ExternalClass
def some_number
456 # Just to exemplify
end
end
# You wrote this code
class ExternalClass
alias_method :some_number_original, :some_number
def some_number
some_number_original + 100
end
end
external = ExternalClass.new
external.some_number # => 556
# You didn't write this code
class ExternalClass
def some_number
456 # Just to exemplify
end
end
# You wrote this code
module SomeModule
def self.included(base)
base.class_eval do
alias_method :some_number_original, :some_number
def some_number
some_number_original + 100
end
end
end
end
e1 = ExternalClass.new
e1.some_number # => 456
ExternalClass.send(:include, SomeModule)
e2 = ExternalClass.new
e2.some_number # => 556
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment