Ruby 如何与`each`迭代器中的上一项进行比较?
更新:对不起,我修复了我的程序:Ruby 如何与`each`迭代器中的上一项进行比较?,ruby,enumerable,Ruby,Enumerable,更新:对不起,我修复了我的程序: 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. str
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
谢谢。您可以使用:
您可以使用:
您可以使用
每个组件
a.each_cons(2) do |first,last|
if last == name
puts 'got you!'
else
name = first
end
end
使用每个\u cons
可能存在的问题是,它在n-1
对之间迭代(如果可枚举的长度为n
)。在某些情况下,这意味着您必须单独处理第一个(或最后一个)元素的边缘情况
在这种情况下,很容易实现一个类似于的函数,但它会为第一个元素产生(nil,elem0)
(而不是每个函数产生(elem0,elem1)
:
由于您可能不想对副本执行更多操作,因此我宁愿将副本保存在一个结构中:
### 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]
更多信息请访问:(David A.Black的冷静回答)试着用文字解释一下意图,代码似乎有问题(特别是x[i-1]
毫无意义)。最好的方法是:给出一些输入和预期输出的示例。每个选项是否仍然合适?
a.each_cons(2) do |first,last|
if last == name
puts 'got you!'
else
name = first
end
end
module Enumerable
def each_with_previous
self.inject(nil){|prev, curr| yield prev, curr; curr}
self
end
end
### 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]