【问题标题】:how to compare to previous item in `each` iterator?如何与“每个”迭代器中的前一项进行比较?
【发布时间】:2012-03-20 00:04:48
【问题描述】:

更新:抱歉,我修复了我的程序:

a = [ 'str1' , 'str2', 'str2', 'str3'  ]
name = ''
a.each_with_index do |x, i |
  if x == name
    puts "#{x} found duplicate."
  else 
    puts x
    name = x  if i!= 0 
  end
end



     output: 
str1
str2
str2 found duplicate.
str3

ruby 语言中还有另一种漂亮的方式来做同样的事情吗?

顺便说一句,实际上。 a 在我的真实案例中是 ActiveRecord::Relation

谢谢。

【问题讨论】:

  • 尝试用文字解释意图,代码似乎有问题(特别是x[i-1] 毫无意义)。最好的方法:举一些输入和预期输出的例子。
  • each_cons 还合适吗?

标签: ruby enumerable


【解决方案1】:

由于您可能想要对重复项做更多的事情而不是 puts,我宁愿将重复项保留在一个结构中:

 ### question's example:
 a = [ 'str1' , 'str2', 'str2', 'str3'  ]
 #  => ["str1", "str2", "str2", "str3"] 
 a.each_cons(2).select{|a, b| a == b }.map{|m| m.first}
 #  => ["str2"] 
 ### a more complex example:
 d = [1, 2, 3, 3, 4, 5, 4, 6, 6]
 # => [1, 2, 3, 3, 4, 5, 4, 6, 6] 
 d.each_cons(2).select{|a, b| a == b }.map{|m| m.first}
 #  => [3, 6] 

更多信息请访问:https://www.ruby-forum.com/topic/192355(David A. Black 的酷回答)

【讨论】:

    【解决方案2】:

    each_cons 可能遇到的问题是它会遍历 n-1 对(如果 Enumerable 的长度是 n)。在某些情况下,这意味着您必须单独处理第一个(或最后一个)元素的边缘情况。

    在这种情况下,很容易实现类似于each_consmethod,但它会为第一个元素产生(nil, elem0)(而不是each_cons,它产生(elem0, elem1)

    module Enumerable
      def each_with_previous
        self.inject(nil){|prev, curr| yield prev, curr; curr}
        self
      end
    end
    

    【讨论】:

      【解决方案3】:

      你可以使用Enumerable#each_cons:

      a = [ 'str1' , 'str2', 'str3' , ..... ]
      name = ''
      a.each_cons(2) do |x, y|
        if y == name
           puts 'got you! '
        else 
           name = x
        end
      end
      

      【讨论】:

        【解决方案4】:

        您可以使用each_cons

        a.each_cons(2) do |first,last|
          if last == name
            puts 'got you!'
          else
            name = first
          end
        end
        

        【讨论】:

          【解决方案5】:

          你可以使用each_cons:

          irb(main):014:0> [1,2,3,4,5].each_cons(2) {|a,b| p "#{a} = #{b}"}
          "1 = 2"
          "2 = 3"
          "3 = 4"
          "4 = 5"
          

          【讨论】:

            猜你喜欢
            • 2022-11-15
            • 2014-10-30
            • 2020-07-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-11-11
            • 2013-06-16
            • 1970-01-01
            相关资源
            最近更新 更多