In Ruby is it possible to reference the array object being generated with a .map
function from within that .map
code block?
A very simple example would be if you were trying to only add unique elements to the returned array and wanted to check to see if that element already existed, which might look like:
array.map{ |v| v unless (reference to array being created by this map function).include?(v) }
I know that functionally this code is unnecessary because you could simply use a .uniq
method on the array or push values into a separate array and check if that array already includes the value, I'm just wondering if it's possible conceptually as I've encountered a few times where such a reference would be useful. Thanks.
Not so far as I know in map. You could however use reduce
or inject
to reference the collection. So:
array.reduce([]) {|memo, v| memo << v unless memo.include? v; memo }
Or...
array.inject([]) do |memo, v|
memo << v unless memo.include? v
memo
end
To clarify some of the questions about reduce
, the final return value for reduce become memo, but if you return the v instead of memo, v becomes the memo, which first pass for an array like [1,2,3,2,1] would be 1. So then your aggregated result gets dropped. So you need to add it to the aggregate and return the aggregate.
Of note: I agree with most commenters, uniq
is the better way to go, both as it seems a more clear statement of intent, but also from a performance standpoint. See this gist for details.