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:
-
$string . ( $condition ? $morestring : '' );
-
@string + ( @condition ? @morestring : '' );
-
@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...
-
@hash.merge( @condition ? { :newkey => 'newvalue' } : {} )
-
# Becomes...
-
@hash + ( @condition ? { :newkey => 'newvalue' } : {} )
Ahhhh, much better. What do you think?
That's why god gave us if statements.
Also, why in hte world are you using array_merge to add a single element to an array, anyway?
I'm missing something..
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?
I guess if you're worried about elegant.. why use the #$%!#$% ternary operator ?
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...)