Created
July 27, 2014 00:51
-
-
Save kasei-san/e1b8ab22bbf8708d130d to your computer and use it in GitHub Desktop.
Iterator パターン ref: http://qiita.com/kasei-san/items/0c3935c6db8666b90287
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "open-uri" | |
class Titles | |
include Enumerable | |
def initialize | |
@urls = [] | |
end | |
def <<(url) | |
@urls << url | |
end | |
def each | |
@urls.each do |url| | |
open(url).read =~ %r|<title>(.*)</title>| | |
yield $1 | |
end | |
end | |
end | |
t = Titles.new | |
t << "http://www.google.co.jp" | |
t << "http://www.yahoo.co.jp" | |
puts t.map(&:upcase) | |
# YAHOO! JAPAN |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
コンテナオブジェクトの要素を列挙する手段を独立させることによって、コンテナの内部仕様に依存しない反復子を提供することを目的とする。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rubyでは、Arrayなどのコンテナオブジェクトが、eachなどのイテレートするメソッドを持っている内部イテレータである |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Items | |
include Enumerable | |
def initialize | |
@items = [] | |
end | |
def <<(item) | |
@items << item | |
end | |
def each | |
@items.each do |item| | |
yield item | |
end | |
end | |
end | |
items = Items.new | |
items << 'abc' | |
items << 'def' | |
items << 'ghi' | |
# Items には実装されていない #each_with_index が使えている!! | |
items.each_with_index do |item, i| | |
puts "#{i} : #{item}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment