Re: Arbitrary mathematical relations, not just hashes

From: Date: Mon, 07 Apr 2008 05:10:42 +0000
Subject: Re: Arbitrary mathematical relations, not just hashes
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-272610@lists.php.net to get a copy of this message
On Sun, Apr 6, 2008 at 11:51 PM, Casey <heavyccasey@gmail.com> wrote: > I hit reply-all... now am I suddenly subscribed to Perl and Ruby lists!?! Huh, didn't notice the cross-posting. But no, you're not subscribed to any new lists. Since we're cross-posting, the translation of my sample would be apropos. Here are a few different takes on a loopless versions in Ruby. Given: color = { :apple => :red, :ruby => :red, :banana => :yellow } This is, I think, the most straightforward: color.keys.find_all { |k| color[k] == :red } But having to repeat the hash name is inelegant. Which leads us to this: color.find_all { |k,v| v == :red }.collect { |p| p[0] } Building up a list from the elements of a Hash would seem to be a natural application of Hash#inject, although the fact that the inject block has to return the accumulator makes it a little less elegant than it could be, IMO: color.inject([]) { |a,p| a << p[0] if p[1] == :red; a } In Perl5 I don't have a better solution than the first one above: my %color = ( apple => 'red', ruby => 'red', banana => 'yellow'); grep { $color{$_} eq 'red' } keys %color; -- Mark J. Reed <markjreed@mail.com>

« previous php.general (#272610) next »