Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to uniq an array case insensitive

As far as i know, the result of

["a", "A"].uniq 

is

["a", "A"]

My question is:

How do I make ["a", "A"].uniq give me either ["a"] or ["A"]

like image 260
Allendog Avatar asked Jul 09 '09 11:07

Allendog


People also ask

What does the Uniq method do in Ruby?

uniq is a Ruby method that returns a new array by removing duplicate elements or values of the array. The array is traversed in order and the first occurrence is kept.


1 Answers

There is another way you can do this. You can actually pass a block to uniq or uniq! that can be used to evaluate each element.

["A", "a"].uniq { |elem| elem.downcase }  #=>  ["A"]

or

["A", "a"].uniq { |elem| elem.upcase }  #=>  ["A"]

In this case though, everything will be case insensitive so it will always return the array ["A"]

like image 96
Eric C Avatar answered Oct 05 '22 10:10

Eric C