ruby 例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 例相关的知识,希望对你有一定的参考价值。

require 'forwardable'

GroceryItem = Struct.new(:name, :quantity, :in_cart) do
  def to_s
    text = "#{quantity} : #{name}"
    in_cart ? "√ #{text}" : "  #{text}"
  end
end


class GroceryList
  extend Forwardable

  def_delegator :@list, :push, :add
  def_delegator :@list, :delete, :remove

  def initialize
    @list = []
  end

  def check(item)
    item.in_cart = true
  end

  def display
    banner
    @list.each { |item| puts item }
  end

  private
  def banner
    puts "~~~~~~~~ Grocery List ~~~~~~~~"
    30.times { print "~" }; puts
  end
end

my_list = GroceryList.new
bread = GroceryItem.new("bread", "1 loaf")
milk = GroceryItem.new("milk", "1 half gallon")
cheese = GroceryItem.new("cheddar cheese", "1 block")
cereal = GroceryItem.new("chocolate chex", "18 boxes")
fruit = GroceryItem.new("apples", "1 bushel")

my_list.add(bread, milk, cheese, cereal, fruit)
my_list.display
puts
my_list.remove(fruit)
my_list.display
puts
my_list.check(milk)
my_list.check(cereal)
my_list.display

以上是关于ruby 例的主要内容,如果未能解决你的问题,请参考以下文章

ruby 例

ruby 例

ruby 将YAML配置文件反序列化为单例实例

ruby 解答例https://codeiq.jp/magazine/2014/03/6633/

ruby on rails(测试用例指定创建数据库表)

05-单例(Singleton)模式Ruby实现