JJB Blog

Wanted: More elegant syntax for adding associations to hashes in PHP and Ruby

Certain situations when adding elements to a hash result in pretty ugly code. I want the experience to be more like string concatenation. Consider these operations on strings, and their hash equivalents:

[php]
$string . ( $condition ? $morestring : ” );
array_merge( $hash, ( $condition ? array( ‘newkey’ => ‘newvalue’ ) : array() )
[/php]

[ruby]
@string + ( @condition ? @morestring : ” );
@hash.merge( @condition ? { :newkey => ‘newvalue’ } : {} )
[/ruby]

Ruby’s direct syntax for hashes is clearly a step forward, but I think this code could be even nicer. Why not alias + and << to merge and merge! ? I suppose there is a bit of a conceptual incongruity when comparing these operations to numbers or strings (because merge will replace elements in the left hash with those from the right hash in the case of key collision). But can you just imagine it…

[ruby]
@hash.merge( @condition ? { :newkey => ‘newvalue’ } : {} )
# Becomes…
@hash + ( @condition ? { :newkey => ‘newvalue’ } : {} )
[/ruby]

Ahhhh, much better. What do you think?


5 Comments

That’s why god gave us if statements.

Posted by Matt Sayler on 29 September 2007 @ 9pm

Also, why in hte world are you using array_merge to add a single element to an array, anyway?

I’m missing something..

Posted by Anonymous on 29 September 2007 @ 9pm

Matt–

I am only adding a single element to the hash in my example, because… it’s an example :)

How would you rewrite the code using an if statement?

Posted by John on 29 September 2007 @ 9pm

I guess if you’re worried about elegant.. why use the #$%!#$% ternary operator ?

Posted by Matt Sayler on 29 September 2007 @ 9pm

That wasn’t the part of the code I was illustrating, it’s irrelevant. But here you go:

(looks like my syntax highlighter inserts a lot of linebreaks when used in comments…)

[ruby]
@hash.merge
if @condition
{ :newkey => ‘newvalue’ }
else
{}
end
# Becomes…
@hash +
if @condition
{ :newkey => ‘newvalue’ }
else
{}
end
[/ruby]

Posted by John on 30 September 2007 @ 11am

Leave a Comment