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