11

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?

7
  • 1
    No, there isn't. I guess @array.compact.uniq should be more efficient. Apr 7, 2015 at 8:16
  • 1
    Nop. But create your own ;)
    – jon snow
    Apr 7, 2015 at 8:19
  • 1
    Using the bang counterparts (@array.uniq! / @array.compact!) to modify the array in-place should be more efficient.
    – Stefan
    Apr 7, 2015 at 8:22
  • 1
    Nah! we don't have :( , I have variety (a | a).compact. :p Apr 7, 2015 at 8:25
  • 1
    I'd try benchmarking, although real world results may depend on the characteristics of your data - which is faster might depend on whether it is more likely that there be large numbers of duplicates or large numbers of nils. Apr 7, 2015 at 9:35

2 Answers 2

7

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
2

No there is no such method.

I think @array.compact.uniq and @array.uniq.compact are equal because both methods have O(N) complexity.

As @Stefan mentioned using methods with ! may decries memory usage.


As an alternative way you may use only uniq method with a block which returns a surely existent element except nil so it will be skipped. For example

@array.uniq { |s| s.nil? ? @array.first : s }

But in this case you have to make sure that the first element of the array is not nil.

1
  • They both have O(n) time complexity. I'm curious: What about memory complexity? Apr 7, 2015 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.