Re: Arbitrary mathematical relations, not just hashes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, Apr 6, 2008 at 11:51 PM, Casey <heavyccasey@xxxxxxxxx> 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@xxxxxxxx>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux