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:
  1. $string . ( $condition ? $morestring : '' );
  2. array_merge( $hash, ( $condition ? array( 'newkey' => 'newvalue' ) : array() )

RUBY:
  1. @string + ( @condition ? @morestring : '' );
  2. @hash.merge( @condition ? { :newkey => 'newvalue' } : {} )

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:
  1. @hash.merge( @condition ? { :newkey => 'newvalue' } : {} )
  2. # Becomes...
  3. @hash + ( @condition ? { :newkey => 'newvalue' } : {} )

Ahhhh, much better. What do you think?

5 Responses to “Wanted: More elegant syntax for adding associations to hashes in PHP and Ruby”


  1. 1 Matt Sayler

    That's why god gave us if statements.

  2. 2 Anonymous

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

    I'm missing something..

  3. 3 John

    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?

  4. 4 Matt Sayler

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

  5. 5 John

    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:
    1. @hash.merge
    2.   if @condition
    3.     { :newkey => 'newvalue' }
    4.   else
    5.     {}
    6.   end
    7. # Becomes...
    8. @hash +
    9.   if @condition
    10.     { :newkey => 'newvalue' }
    11.   else
    12.     {}
    13.   end

Leave a Reply




Close
Powered by ShareThis