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.
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 downcase
able. Otherwise, you'll get NoMethodError
s.
You can eliminate the non-downcase
able elements like this:
data.select{|item| item.respond_to? :downcase}.map(&:downcase).uniq
although if the only non-downcase
able elements are nil
s, you can eliminate those by simply compact
ing the array first:
data.compact.map(&:downcase).uniq
Note that ary.map(&:foo)
is shorthand for ary.map {|item| item.foo}
.