(self[key] ||= []) << value
Now I wanna make an array of values unique.
So the code above becomes
unless ((self[key] ||= ).include? value )
self[key].push value
end
Is there a nicer way?
RR
(self[key] ||= []) << value
Now I wanna make an array of values unique.
So the code above becomes
unless ((self[key] ||= ).include? value )
self[key].push value
end
Is there a nicer way?
RR
Maybe just:
self[key] << value unless (self[key] ||= ).include? value
On Wednesday 04 December 2002 11:44 am, Roman Rytov wrote:
(self[key] ||= []) << value
Now I wanna make an array of values unique.
So the code above becomes
unless ((self[key] ||= ).include? value )
self[key].push value
end
Is there a nicer way?
RR
–
Bruce R. Williams :: [iusris/#ruby-lang] :: http://www.codedbliss.com
‘It does not require a majority to prevail, but rather an irate,
tireless minority keen to set brush fires in people’s minds.’
– Samuel Adams
PS:
You could also do:
((self[key] ||= []) << value).uniq!
… but that’s probably less efficient and arguably more ugly-- though shorter
(for educational purposes only)
On Wednesday 04 December 2002 05:15 pm, Bruce Williams wrote:
self[key] << value unless (self[key] ||= ).include? value
–
Bruce R. Williams :: [iusris/#ruby-lang] :: http://www.codedbliss.com
‘It does not require a majority to prevail, but rather an irate,
tireless minority keen to set brush fires in people’s minds.’
– Samuel Adams
What if you use Hash instead of Array as a value of self[key]? Then, as keys
are unique by definition, you could have something like:
(self[key] ||= Hash.new)[value] = true # or just nil
and later you reference it as
self[key].keys
Regards,
Gennady.
----- Original Message -----
From: “Bruce Williams” bruce@codedbliss.com
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Wednesday, December 04, 2002 2:23 PM
Subject: Re: MultiMap
On Wednesday 04 December 2002 05:15 pm, Bruce Williams wrote:
self[key] << value unless (self[key] ||= ).include? value
PS:
You could also do:
((self[key] ||= ) << value).uniq!
… but that’s probably less efficient and arguably more ugly-- though
shorter
(for educational purposes only)
–
Bruce R. Williams :: [iusris/#ruby-lang] :: http://www.codedbliss.com
‘It does not require a majority to prevail, but rather an irate,
tireless minority keen to set brush fires in people’s minds.’
– Samuel Adams