ブロックの戻り値使ったり、[]を再定義したり。
プログラミングRubyを鞄に入れ近くのカフェへ。
まったりと読もうと思ったら隣の席に座ったおじさんが「バカバカバカバカ…」「しねしねしねしねしね…」と延々と呟き続けていて、注文したココアの味がしないは、本の内容はなかなか頭に入ってこないはと大変な思いをした。
それでもどうにか覚えたことをメモメモ。
#!/usr/bin/env ruby class Product def initialize(name) @name = name end attr_accessor :name end class Products def initialize() @list = Array.new @list << Product.new('hoge') @list << Product.new('huga') end # obj[index] def [](index) return @list[index] end # obj[index] = valみたいにできる def []=(index, val) @list[index] = val end def find_index @list.each_with_index do |product, i| # ブロックが渡されているか? if block_given? # ブロックから返された値で分岐 if yield(product) return i end else return nil end end end # &付きの引数はブロック def send(product, &action) action.call(product) end end products = Products.new p products[0] p products[1] products[2] = Product.new('hoji') p products[2] p products.find_index { |product| product.name == 'hoge'} p products.find_index products.send(products[0]) { |product| puts "#{product.name} was sent"}
結果。
#<Product:0x2407c @name="hoge"> #<Product:0x24054 @name="huga"> #<Product:0x23fdc @name="hoji"> 0 nil hoge was sent
- 作者: Dave Thomas,Chad Fowler,Andy Hunt,まつもとゆきひろ,田和勝
- 出版社/メーカー: オーム社
- 発売日: 2006/08/26
- メディア: 大型本
- 購入: 7人 クリック: 270回
- この商品を含むブログ (152件) を見る