⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 13 - aliasing methods.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
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  alias :unit_cost= :unit_price=endbacon = InventoryItem.new("Chunky Bacon", 3.95)bacon.price(100)                                   # => 395.0bacon.cost(100)                                    # => 395.0bacon.unit_price                                   # => 3.95bacon.unit_cost                                    # => 3.95bacon.unit_cost = 3.99bacon.cost(100)                                    # => 399.0#---class Array  alias :len :lengthend[1, 2, 3, 4].len                                    # => 4#---class Array  alias :length_old :length  def length    return length_old / 2  end  end#---array = [1, 2, 3, 4]array.length                                       # => 2array.size                                         # => 4array.length_old                                   # => 4#---class Array  alias :length :length_oldendarray.length                                       # => 4#---class InventoryItem  def cost(*args)    price(*args)  endend#---bacon.cost(100)                                    # => 399.0require 'bigdecimal'require 'bigdecimal/util'class InventoryItem  def price(quantity=1, sales_tax=BigDecimal.new("0.0725"))    base_price = (unit_price * quantity).to_d    price = (base_price + (base_price * sales_tax).round(2)).to_f  endendbacon.price(100)                                   # => 427.93bacon.cost(100)                                    # => 427.93#---bacon.cost(100, BigDecimal.new("0.05"))            # => 418.95#---

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -