Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Last active February 22, 2016 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoelQ/674ad482882be74c2e3f to your computer and use it in GitHub Desktop.
Save JoelQ/674ad482882be74c2e3f to your computer and use it in GitHub Desktop.

Ruby docs for Array#uniq

From the docs:

uniq → new_ary uniq { |item| ... } → new_ary Returns a new array by removing duplicate values in self.

If a block is given, it will use the return value of the block for comparison. It compares values using their hash and eql? methods for efficiency. self is traversed in order, and the first occurrence is kept.

class Uniq
attr_reader :item
def initialize(item)
@item = item
end
end
class Eql < Uniq
def eql?(other)
self == other
end
end
puts "Only `eql?` defined:"
puts "Running: [Eql.new(1), Eql.new(1)].uniq"
p [Eql.new(1), Eql.new(1)].uniq
puts
class Hsh < Uniq
def hash
item.hash
end
end
puts "Only `hash` defined:"
puts "Running: [Hsh.new(1), Hsh.new(1)].uniq"
p [Hsh.new(1), Hsh.new(1)].uniq
puts
class EqlAndHash < Uniq
def eql?(other)
other.item == self.item
end
def hash
item.hash
end
end
puts "Both `hash` and `eql?` defined"
puts "Running: [EqlAndHash.new(1), EqlAndHash.new(1)].uniq"
p [EqlAndHash.new(1), EqlAndHash.new(1)].uniq
puts
class DoubleEqualsAndHash < Uniq
def ==(other)
other.item == self.item
end
def hash
item.hash
end
end
puts "Both `hash` and `==` defined"
puts "Running: [DoubleEqualsAndHash.new(1), DoubleEqualsAndHash.new(1)].uniq"
p [DoubleEqualsAndHash.new(1), DoubleEqualsAndHash.new(1)].uniq
Only `eql?` defined:
Running: [Eql.new(1), Eql.new(1)].uniq
[#<Eql:0x007facd400ed48 @item=1>, #<Eql:0x007facd400ed20 @item=1>]
Only `hash` defined:
Running: [Hsh.new(1), Hsh.new(1)].uniq
[#<Hsh:0x007facd400e938 @item=1>, #<Hsh:0x007facd400e910 @item=1>]
Both `hash` and `eql?` defined
Running: [EqlAndHash.new(1), EqlAndHash.new(1)].uniq
[#<EqlAndHash:0x007facd400e5a0 @item=1>]
Both `hash` and `==` defined
Running: [DoubleEqualsAndHash.new(1), DoubleEqualsAndHash.new(1)].uniq
[#<DoubleEqualsAndHash:0x007facd400e2a8 @item=1>, #<DoubleEqualsAndHash:0x007facd400e258 @item=1>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment