【问题标题】:In ruby / rails how do I make this helper for a common loop?在 ruby​​ / rails 中,我如何为公共循环制作这个助手?
【发布时间】:2016-10-11 19:03:53
【问题描述】:

我一直在写这段代码,它比较两个相同的数组,如果它们是同一个项目:

items.each_with_index do | x, i |
    items.each do | y, j |
        if x.id != y.id
            #... do some things
        end
    end
end

我真正想写的是:

items.compare_each do | x, y, i, j |
    #... do some things
end

您将如何在 ruby​​/rails 中编写帮助程序?还是已经存在了?

【问题讨论】:

  • 您能提供更多的上下文吗? items 是什么?你是如何使用这个循环的?
  • 我只看到一个数组,items ...循环通常是针对单个数组的吗?
  • Items 只是任何一组记录,但它们都有一个 id。是的,抱歉,它正在将同一个数组与自身进行比较。

标签: ruby-on-rails ruby helpers


【解决方案1】:

假设您尝试将单个数组中的每个元素与该数组中的每个其他元素进行比较,如您的示例代码所示(而不是像您的文本所述那样将两个数组相互比较),您需要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]]

上面的例子也使用了argument destructuring

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    相关资源
    最近更新 更多