ruby 迭代数组的前 n 个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9780695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate over the first n elements of an array
提问by Yosef
How can I iterate up to four objects of an array and not all? In the following code, it iterates over all objects. I need only the first four objects.
如何迭代最多四个数组对象而不是全部?在以下代码中,它遍历所有对象。我只需要前四个对象。
objects = Products.all();
arr=Array.new
objects.each do |obj|
arr << obj
end
p arr
Can it be done like objects=objects.slice(4), or is iteration the only way?
可以这样做objects=objects.slice(4)吗,还是迭代是唯一的方法?
Edit:
编辑:
I also need to print how many times the iteration happens, but my solution objects[0..3](thanks to answers here) long.
我还需要打印迭代发生的次数,但我的解决方案objects[0..3](感谢这里的答案)很长。
i=0;
arr=Array.new
objects[0..3].each do |obj|
arr << obj
p i;
i++;
end
采纳答案by Hyman
I guess the rubyst way would go by
我猜红宝石的方式会过去
arr=Array.new
objects[0..3].each do |obj|
arr << obj
end
p arr;
so that with the [0..3]you create a subarray containing just first 4 elements from objects.
这样[0..3]你就可以创建一个只包含对象的前 4 个元素的子数组。
回答by Kate
You can get first n elements by using
您可以通过使用获得前 n 个元素
arr = objects.first(n)
回答by Mladen Jablanovi?
Enumerable#takereturns first nelements from an Enumerable.
Enumerable#taken从 Enumerable返回第一个元素。
回答by Automatico
arr = objects[0..3]
Thats all. You dont need the rest
就这样。你不需要剩下的
回答by Kyle
You can splice the array like this objects[0,4]
你可以像这样拼接数组 objects[0,4]
objects[0,4]is saying: start at index 0 and give me 4 elements of the array.
objects[0,4]是说:从索引 0 开始并给我数组的 4 个元素。
arr = objects[0,4].inject([]) do |array, obj|
array << obj
end
p arr

