【问题标题】:@things.each or 5.times do |t|@things.each 或 5.times 做 |t|
【发布时间】:2012-03-11 19:11:40
【问题描述】:

有没有办法让迭代器在对象为 nil 时也能进行迭代?

例如,我想从我的应用程序中剥离我的视图并为设计师创建一个虚拟应用程序。

所以我希望它迭代或循环。

如何做到这一点?

我刚刚找到了一种方法

<%
   (@messages.count == 0 ? Array.new(5).map { Message.new } : @messages.each).each do |m|         
%>

【问题讨论】:

  • 如果你不打算修改你的消息,Array.new(5, Message.new) 会更快,除了@messages.each => @messages,你不需要创建枚举器。

标签: ruby iteration


【解决方案1】:

答案只在你的问题中,即使你没有任何对象,你也可以使用迭代 5 次

5.times do |i|
  puts "Dummy page"
end

【讨论】:

    【解决方案2】:

    你应该可以使用这样的东西:

    (@things || dummy_things).each do |thing|
      # do something with thing
    end
    
    def dummy_things
      dummies = []
      5.times do
        dummies.push(Thing.new)
      end
      dummies
    end
    

    因此,如果 @thingsnil,则它的作用是迭代虚拟事物,否则仅迭代 @things

    编辑

    正如 Victor 所提到的,dummy_things 的更简洁版本应该是这样的:

    def dummy_things
      (0..4).map{ Thing.new }
    end
    

    【讨论】:

    • 感觉(0..4).map{ Thing.new }比手动做要好很多
    • 我同意。 (0..4).map{ Thing.new } 看起来更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多