Mr eel

A Mullion Ways to Do the One Thing

As much as I like Ruby, sometimes I see a feature that just makes me ask why. WHY? Specifically, when you have two features that do exactly the same thing, why implement both? The best argument for redundant features is that one is a short cut for a common argument. The best examples are the various literals.


# Hash
{:yay => 'spasm', :hoon => 'town'}
# Array
[1, 2, 3, 4]
%w(array of four words)
# Integers and floats
1
1.2
# Strings
"Yes, this is actually a literal"
# Regular Expressions
/(\w+)\/|./
# Ranges
1..100

And more… There are loads of ‘em! Literals are one of the nice things about Ruby. They are also sadly, one of the worst. Why? Because many of them are redundant. One that I came across more recently made me quirk my brows:


# Create a hash
{1 => 2, 3 => 4} #=> {1 => 2, 3 => 4}
{1,2,3,4}        #=> {1 => 2, 3 => 4}

The first is the most common literal for creating hashes. It’s perfect, since you’re listing the pairs that go into your new hash and you can see how the keys are related to the values. The second one is just a shorter version. More to the point, it’s a more opaque version. Why is it even there?

Just one more example:


# Create an array
%w(array of words)  #=> ['array', 'of', 'words']
%w'array of words'  #=> ['array', 'of', 'words']
%w{array of words}  #=> ['array', 'of', 'words']

If you haven’t seen this literal before, it just takes a string and treats each separate word as an entry in the array — it’s equivalent to doing "array of words".split(' '). This means you can’t have multi-word entries, but it’s a super useful shortcut. The first is the most commonly used. The other two do the same thing, but use different characters to delineate the string.

It’s a tiny thing to be sure, but I really don’t like having all these different shortcuts to do the same thing. It’s inelegant. Sadly, new versions of Ruby will have more literals.


# Yet another hash literal
{key: 'value', pairs: 'augogo'}  #=> {:key => 'value', :pairs => 'augogo'}

More deprecations in Ruby I say! Pick one good thing and stick with it.

But… I still love you Ruby *hugs*.

Posted on December 4th, 2007 | There are 2 comments

Comments

Axel on December 11, 2007

The “optional =>” in the hash and the %w() functionality is most likely an attempt to be somewhat perl-like, and the {key:value} hash literal will attract javascript programmers and easy support for JSON syntax. Watch out ruby, by attempting to appeal to everyone, you may end up appealing to no one. By spreading yourself too thin to cater to all styles, you lose your distinctiveness.

Max Williams on March 6, 2008

I’m with you on the hashes - I expected this

{:one, :two, :three, :four}

to create this

{:one => nil, :two => nil, :three => nil, :four => nil}

I still think it would be nicer if it did work like that.

Add a comment

All contents © 2005—2007 Luke Matthew Sutton