Ruby/Method/alias
Материал из Wiki.crossplatform.ru
Содержание |
Alias a old method a new name, then change the implementation of old method
class Array alias :length_old :length def length return length_old / 2 end end array = [1, 2, 3, 4] array.length # => 2 array.size # => 4 array.length_old # => 4 class Array alias :length :length_old end array.length # => 4
Aliasing Methods
class MyClass attr_accessor :name, :unit_price def initialize(name, unit_price) @name, @unit_price = name, unit_price end def price(quantity=1) @unit_price * quantity end # Make MyClass#cost an alias for MyClass#price alias :cost :price # The attr_accessor decorator created two methods called "unit_price" and # "unit_price=". I"ll create aliases for those methods as well. alias :unit_cost :unit_price alias :unit_cost= :unit_price= end bacon = MyClass.new("Bacon", 3.95) bacon.price(100) # => 395.0 bacon.cost(100) # => 395.0 bacon.unit_price # => 3.95 bacon.unit_cost # => 3.95 bacon.unit_cost = 3.99 bacon.cost(100) # => 399.0
Create a Wrapper method to alias
class MyClass attr_accessor :name, :unit_price def initialize(name, unit_price) @name, @unit_price = name, unit_price end def price(quantity=1) @unit_price * quantity end alias :cost :price alias :unit_cost :unit_price alias :unit_cost= :unit_price= def cost(*args) price(*args) end end bacon = MyClass.new("Bacon", 3.95) bacon.cost(100) # => 399.0
Give length a new name
class Array alias :len :length end [1, 2, 3, 4].len # => 4
Redefining Backquotes
alias old_backquote ` def `(cmd) result = old_backquote(cmd) if $?!= 0 fail "Command #{cmd} failed: #$?" end result end print `date` print `data`