Search code examples
arraysrubynullunique

How do I get unique elements, in a case insensitive way in Ruby, and accounting for nil elements?


I'm using Ruby 2.4. How do I get unique elements, in a case-insensitive way, from an array but accounting for nil elements? I thougth this was the solution

data.map{|i| i || i.downcase}.uniq

but even after all my learning I'm still getting the error

NoMethodError: undefined method `downcase' for nil:NilClass

when one of the elements in teh array is nil.


Solution

  • Your question says you want unique elements in a case-insensitive way. @Glyoko's answer does that.

    If you want the elements all converted to lowercase (or uppercase) as well, that's different from what you asked.

    data.map(&:downcase).uniq will work if all the elements of data are downcaseable. Otherwise, you'll get NoMethodErrors.

    You can eliminate the non-downcaseable elements like this:

    data.select{|item| item.respond_to? :downcase}.map(&:downcase).uniq
    

    although if the only non-downcaseable elements are nils, you can eliminate those by simply compacting the array first:

    data.compact.map(&:downcase).uniq
    

    Note that ary.map(&:foo) is shorthand for ary.map {|item| item.foo}.