Ruby编程中的方法别名、面向切面编程、软件契约及XML处理
方法别名
在编程中,为方法选择一个完美的名称并非易事。有时可能没有合适的名称,有时又有太多好名称可供选择,这会让用户难以记住方法的“正确”名称。Ruby提供了 alias 命令来创建方法别名,帮助解决这个问题。
例如,在 InventoryItem 类中,为了避免用户将 price 方法误记为 cost ,可以使用 alias 创建别名:
class InventoryItem
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 InventoryItem#cost an alias for InventoryItem#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
超级会员免费看
订阅专栏 解锁全文
3435

被折叠的 条评论
为什么被折叠?



