30th
Fri
Enumeratorに関する妄想
こんな風に書いてみたいと思った。
1 <% posts.each.if do %> 2 <ul> 3 <% iterate do |post| %> 4 <li><%= h(post.body) %></li> 5 <% end %> 6 </ul> 7 <% end.else %> 8 <div> 9 Not yet posted. 10 </div> 11 <% end %>
Enumerator
追記
という事で、作ってみた。
1 module Enumerable2 class Iterator 3 def initialize (enumerable ) 4 @enumerable = enumerable 5 end 6 7 def iterate(&block) 8 block.call(@enumerable .next) while true 9 rescue StopIterat ion 10 end 11 end 12 13 class Enumerator 14 def if(&block) 15 Iterator.new(self).instance_e val(&block) if count > 0 16 self 17 end 18 19 def else(&block) 20 block.call if count == 0 21 end 22 end 23 end
posted by
genki
on Fri 30 Jan 2009
at 18:56