简体   繁体   English

在 ruby​​ / rails 中,我如何为公共循环制作这个助手?

[英]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.

相关问题 在 Rails 中,如何制作循环助手? - In Rails, how can I make a loop helper? 如何让工厂可以使用辅助方法? (导轨,Rspec) - How do I make a helper method available to factories? (Rails, Rspec) Ruby on Rails-如何从帮助文件中创建一个小部件? - Ruby on Rails - how to make a clippy widget work from a helper file? 如何在轨道上的ruby中向表单添加类而不设置/覆盖现有的默认助手类? - How do I add a class to a form in ruby on rails without setting / overriding the existing default helper class? 在Ruby on Rails 4中,如何在forms_for助手中设置与模型无关的属性? - In ruby on rails 4, how do I set an attribute in the forms_for helper that is not associated with a model? 如何在Rails上的ruby中对for循环的结果进行排序 - How do I sort the outcome of my for-loop in ruby on rails Ruby on Rails:如何在link_to帮助器中添加类? - Ruby on Rails: how do you add a class in a link_to helper? 如何在 Ruby on Rails 迁移中使列唯一并为其编制索引? - How do I make a column unique and index it in a Ruby on Rails migration? 如何在Ruby on Rails中使对象成为模型的属性? - How do I make an object a property of a model in Ruby on Rails? 如何从Ruby on Rails帮助方法返回javascript? - How can I return javascript from a Ruby on Rails helper method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM