1 ruby arrays each for-loop curly-braces
来自其他语言,其中 for 循环是主要的迭代方式,我很好奇是否有更好的 Ruby 风格的方法来实现以下功能:
q=[5,1,7,9,0,3,6,8,0]
for i in 0..q.size/3-1
do one thing with q[0+i*3]
do another one with q[1+i*3]
third operation on q[2+i*3]
end
Run Code Online (Sandbox Code Playgroud)
谢谢!
提交的有问题的代码实际上可以工作,但是知道 for in Ruby 在幕后使用每个代码,我不确定使它更加紧凑和高效的最佳方法是什么。
最 Ruby 的方式来做到这一点可能是使用Enumerable#each_slice:
q.each_slice(3) do |first, second, third|
# do something with `first`
# do another thing with `second`
# third operation with `third`
end
Run Code Online (Sandbox Code Playgroud)
例如:
q.each_slice(3) do |first, second, third|
p({ first:, second:, third: })
end
# { first: 5, second: 1, third: 7 }
# { first: 9, second: 0, third: 3 }
# { first: 6, second: 8, third: 0 }
Run Code Online (Sandbox Code Playgroud)
一般来说,任何程序中最重要的操作之一是“迭代东西”(或者更一般地说,遍历、转换、过滤、构建和折叠集合),而在 Ruby 中,这是由 mixin 处理的Enumerable。研究和理解这个 mixin 的文档对于编写良好的、惯用的 Ruby 代码至关重要。
作为(稍微夸张的)一般规则,如果您必须在 Ruby 中编写循环或手动调整索引或计数器,那么您很可能做错了什么。事实上,大多数现代编程语言都附带强大的算法、数据结构和集合库,这不仅适用于 Ruby,而且几乎普遍适用。