[英]In ruby / rails how do I make this helper for a common loop?
I write this bit of code all the time, it compaires two of the same array expect if they're the same item:我一直在写这段代码,它比较两个相同的数组,如果它们是同一个项目:
items.each_with_index do | x, i |
items.each do | y, j |
if x.id != y.id
#... do some things
end
end
end
What I'd really like to write is:我真正想写的是:
items.compare_each do | x, y, i, j |
#... do some things
end
How would you go about writing a helper that in ruby/rails?你会如何编写一个用 ruby/rails 编写的帮助程序? Or even does it already exist?或者甚至它已经存在?
Assuming you're trying to compare each element in a single array with every other element in that array, as your example code shows (rather than comparing two arrays with each other, as your text states), you want Array#combination
, possibly in conjunction with Enumerable#each_with_index
if the indexing is important:假设您试图将单个数组中的每个元素与该数组中的每个其他元素进行比较,如您的示例代码所示(而不是将两个数组相互比较,如您的文本所述),您需要Array#combination
,可能在如果索引很重要,请与Enumerable#each_with_index
结合使用:
%i{a b c d e}.each_with_index.to_a.combination(2) {|(x,i),(y,j)| p [x,y,i,j] }
[:a, :b, 0, 1]
[:a, :c, 0, 2]
[:a, :d, 0, 3]
[:a, :e, 0, 4]
[:b, :c, 1, 2]
[:b, :d, 1, 3]
[:b, :e, 1, 4]
[:c, :d, 2, 3]
[:c, :e, 2, 4]
[:d, :e, 3, 4]
=> [[:a, 0], [:b, 1], [:c, 2], [:d, 3], [:e, 4]]
The above example also makes use of argument destructuring .上面的例子也使用了参数解构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.