更新:抱歉,我修复了我的程序:
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
Run Code Online (Sandbox Code Playgroud)
是否有另一种美妙的ruby语言方式来做同样的事情?
顺便说一句,实际上.a是ActiveRecord::Relation在我的真实案例.
谢谢.
Mla*_*vić 19
您可能遇到的问题each_cons是它遍历n-1对(如果Enumerable的长度是n).在某些情况下,这意味着您必须单独处理第一个(或最后一个)元素的边缘情况.
在这种情况下,实现类似的方法非常容易each_cons,但是会产生(nil, elem0)第一个元素(相反each_cons,它产生(elem0, elem1):
module Enumerable
def each_with_previous
self.inject(nil){|prev, curr| yield prev, curr; curr}
self
end
end
Run Code Online (Sandbox Code Playgroud)
Vas*_*ich 13
你可以使用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"
Run Code Online (Sandbox Code Playgroud)
您可以使用 each_cons
a.each_cons(2) do |first,last|
if last == name
puts 'got you!'
else
name = first
end
end
Run Code Online (Sandbox Code Playgroud)