在Ruby早期逃避.each {}迭代 [英] escaping the .each { } iteration early in Ruby

查看:147
本文介绍了在Ruby早期逃避.each {}迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

 c = 0  
 items.each { |i|  
   puts i.to_s    
   # if c > 9 escape the each iteration early - and do not repeat  
   c++  
 }  

我想抓住前10个项目然后离开每个循环。

I want to grab the first 10 items then leave the "each" loop.

我该用什么替换注释行?有更好的方法吗? Ruby idiomatic更多的东西?

What do I replace the commented line with? is there a better approach? something more Ruby idiomatic?

推荐答案

虽然中断解决方案有效,但我认为更实用的方法真的适合这个问题。你想要前10个元素并打印出来,试试

While the break solution works, I think a more functional approach really suits this problem. You want to take the first 10 elements and print them so try

items.take(10).each { |i| puts i.to_s }

这篇关于在Ruby早期逃避.each {}迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆