I'm working with rails, it happens that when I run my project, I get to the point where I only have to have duplicate values inside the arrays, therefore I have to eliminate the NOT repeated values, for example:
array=[2017,2017,2018,2018,2019]
in this case the value 2019 should be eliminated, since it is not repeated
What I have is the following:
def saca_no_repetido(array)
for i in 0...array.length
if(array[i]!=array[i+1] && array[i+1]!=nil)
array.delete_at(i)
end
end
return array
end
Ruby has methods (via the module
Enumerable
) to manipulate collections; for your specific case, you can useselect
andcount
:This solution is the simplest, however it is slow if you decide to apply it to large arrays; in that case, you could use the
group_by
,select
andflat_map
:This option is less readable, but faster.
The use of
Enumerable
is very common in Ruby and is what the community recommends to use (it is more idiomatic ), as opposed to the use offor
, which you will find in very specific solutions (it is more common to useeach
).Due to the problem you express, the following array should be returned:
For that I have modified a little the code that you have shared:
Result
Explanation
I have put a
for
nest, this so that every time it goes through a data, it goes through the same array again in search of another data that is the same.I created a closure
if
, which clauses if the data of the firstfor
coincides with that of the second, also that the position is not the same in both, since the same data would be found and not a different one.If an equal data is found in a different position in
array
the variableencontrado
increases in1
if it is at the end is0
, it means that it is a data that is not repeated and is eliminated from the array.It also works if the repeated data is not next to each other:
Result