31st Sat
Enumeratorに関する妄想
こんな風に書いてみたいと思った。
html>>
<% posts.each.if do %>
-
<% iterate do |post| %>
- <%= h(post.body) %> <% end %>
Not yet posted.
<% end %>
<<--
Enumerator#ifを作れば実現出来そうだ。
**追記**
という事で、作ってみた。
ruby>>
module Enumerable
class Iterator
def initialize(enumerable)
@enumerable = enumerable
end
def iterate(&block)
block.call(@enumerable.next) while true
rescue StopIteration
end
end
class Enumerator
def if(&block)
Iterator.new(self).instance_eval(&block) if count > 0
self
end
def else(&block)
block.call if count == 0
end
end
end
<<--posted by
genki on Sat 31 Jan 2009 at 09:31 with 0 comments