Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array method that combines 'uniq' and 'compact'

Tags:

ruby

I am trying to find unique elements in an array and remove the nil values from it. My solution looks like this:

@array = [1, 2, 1, 1, 2, 3, 4, nil, 5, nil, 5] 
@array.uniq.compact # => [1, 2, 3, 4, 5] 

Is there any single method that does both the operations? If not, which is efficient, @array.uniq.compact or @array.compact.uniq?

like image 802
webster Avatar asked Apr 07 '15 08:04

webster


1 Answers

No, but you can append them in any order you like i.e.

array.uniq.compact
array.compact.uniq

As pointed out by phts, you can pass a block to uniq but I don't see that being a very helpful alternative over uniq.compact.

For better speed however, something like the following might help:

[].tap do |new_array|
  hash = {}
  original_array.each do |element|
    next if element.nil? || !hash[element].nil?
    new_array << (hash[element] = element)
  end
end

Finally, if speed isn't an issue and you'll be frequently using this method, then you could create your own method:

class Array
  def compact_uniq
    self.compact.uniq
  end

  def compact_blank # in case you want to remove all 'blanks' as well
    self.compact.reject(&:blank?)
  end
end
like image 157
SHS Avatar answered Feb 05 '23 23:02

SHS