HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Implementing Array#uniq in Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayimplementingrubyuniq

Problem

I've implemented a working version of Array#uniq in Ruby to answer the question here: http://www.rubeque.com/problems/like-a-snowflake, but I'd like to see if there's ways to clean up my code or some better practices I should follow? This is my version:

class Array
  def uniq(&block)
    objs = []
    yield_vals = []
    self.each do |obj|
      yield_val = yield obj
      unless yield_vals.include?(yield_val)
        yield_vals.push(yield_val)
        objs.push(obj)
      end
    end
    objs
  end
end

Solution

For one, I'd use the << operator rather than push just out of convention.

Second, you still have other Array/Enumerable methods at your disposal. So there's no need to create a new array and add unique items to it. Try filtering the array instead.

Update: Whoo boy, I was still asleep when I wrote that first answer. In my defense it was early

You can actually just do

def uniq(&block)
  group_by(&block).values.map(&:first)
end


As for my previous answer... well, I did say it could be done better. Just pretend it didn't happen.

Code Snippets

def uniq(&block)
  group_by(&block).values.map(&:first)
end

Context

StackExchange Code Review Q#36027, answer score: 3

Revisions (0)

No revisions yet.