Silly question I think, but I've searched high and low for a definitive answer on this and found nothing.
我认为这是一个愚蠢的问题,但是我在这个问题上找到了一个明确的答案并没有找到任何答案。
array.each_with_index |row, index|
puts index
end
Now, say I only want to print the first ten items of the array.
现在,假设我只想打印数组的前十项。
array.each_with_index |row, index|
if (index>9)
break;
end
puts index
end
Is there a better way than this?
有比这更好的方法吗?
2 个解决方案
#1
13
Use Enumerable#take
:
使用Enumerable#take:
array.take(10).each_with_index |row, index|
puts index
end
If the condition is more complicated, use take_while
.
如果条件更复杂,请使用take_while。
The rule of thumb is: iterators might be chained:
经验法则是:迭代器可能被链接:
array.take(10)
.each
# .with_object might be chained here or there too!
.with_index |row, index|
puts index
end
#2
3
Another solution is to use Enumerable#first
另一个解决方案是首先使用Enumerable#
array.first(10).each_with_index do |row, index|
puts index
end
#1
13
Use Enumerable#take
:
使用Enumerable#take:
array.take(10).each_with_index |row, index|
puts index
end
If the condition is more complicated, use take_while
.
如果条件更复杂,请使用take_while。
The rule of thumb is: iterators might be chained:
经验法则是:迭代器可能被链接:
array.take(10)
.each
# .with_object might be chained here or there too!
.with_index |row, index|
puts index
end
#2
3
Another solution is to use Enumerable#first
另一个解决方案是首先使用Enumerable#
array.first(10).each_with_index do |row, index|
puts index
end