"Florian Gross" <flgr / ccan.de> schrieb im Newsbeitrag 
news:36482aF4tni5tU1 / individual.net...
> Pit Capitain wrote:
>
>> Trans schrieb:
>>
>>> Has anyone, could anyone, write a Ruby version of this method? I'm not
>>> sure what its supposed to do exaclty. Id like to see source.
>>
>> No problem:
>>
>>   require 'set'
>>
>>   class Array
>>     def uniq_by
>>       result = []
>>       values = Set.new
>>       each do |elem|
>>         value = yield elem
>>         unless values.include? value
>>           values << value
>>           result << elem
>>         end
>>       end
>>       result
>>     end
>>   end
>>
>>   p ( 0 .. 9 ).to_a.uniq_by { |x| x % 4 }  # => [0, 1, 2, 3]
>>
>> I bet Robert will transform this into a version using inject ;-)
>
> module Enumerable
>   def uniq_by()
>     inject([]) do |state, item|
>       value = yield(item)
>       state.include?(value) ? state : state + [item]
>     end
>   end
> end

Hmmm...  When deciding whether to include an element or not you mix values 
and converted values.  That's not the same as what the implementation above 
does.

Also (as optimization) you could use "state << item" instead of "state + 
[item]" because Array#<< returns self.  This saves you a lot temporary 
1element arrays and avoids creating new arrays all the time (Array#+ creates 
a new Array). :-)

Kind regards

    robert