I don’t like the Ruby 1.9 hash syntax

June 20, 2011 § 67 Comments

There, I said it, I don’t like it. And I don’t know why you do either.

I assume you like it anyway, everyone else I talk to seems to. My heart sank over and over again whilst I was at the recent and saw respected rubyist after respected rubyist using the new Ruby 1.9 hash syntax in their presentations.

I just don’t get it.

But I’m not one to just moan. I plan to justify my feelings. Then maybe you can tell me why you do like it?

My friend the hash rocket

I like the hash rocket (not least because it’s a rocket) and I know it’s not going away. However, these are my reasons for disliking the new syntax.

Keys are restricted

According to this Stack Overflow answer, keys are limited to something like /^[a-zA-Z_][a-zA-Z0-9]*$/. I like using any object I choose as a key.

# Ruby 1.8 Syntax
{:this => 'syntax', 'is' => 'fun', #<And:0x10036bb58> => 'flexible'}
# Ruby 1.9 syntax
{this: 'syntax', 'will': 'cause', #<Nasty:0x10031bf85>: 'errors'}

Obviously mixing key styles is not helpful, but surely there are situations you’ve found yourself using an integer, a string with a dash in it or even an arbitrary object as a key.

It is misleading

Your input appears to be a string of some sort, but your hash keys are symbols

hash = { test: 'hash' }
# => { :test => 'hash' }
hash.test
# => NoMethodError (works in JavaScript!)
hash['test']
# => nil
hash[:test]
# => 'hash' (hooray!)

Similarity to other languages

I half understand the desire to make languages act similarly so swapping between them is easier. The new syntax mimics JSON which is important for Ruby, or at least Rails, developers as JavaScript is one of the languages we’ll switch to more frequently. In theory that makes sense. However, I like the distinction. I know when I am typing Ruby and will type in the same style as I and everyone else always has. As far as I can tell, changing the hash syntax to look the same as JavaScript (or other languages) has as much point as starting to write variables in camel case in Ruby.

Backwards compatibility

Obviously this new feature is not part of Ruby 1.8. It wouldn’t be a new feature if it was. However, for something so fundamental to the language I don’t understand why we need new ways of writing it that will break older versions. Particularly, if someone decides to write or update a gem to use the 1.9 syntax and no other 1.9 features, then that gem will become unavailable for anyone still using 1.8 (of which I am sure there are more than a few) for no good reason. Normally we could argue that as the language progresses and we use 1.8 less and less, that we could migrate to using this syntax only, but I don’t think that will be the case, given the restrictions I mention earlier.

Mixing it up

When writing code in teams or contributing to larger projects, code style is important and the existence of two different syntaxes inevitably means that a project will end up with both. This is poor for consistency and whilst it could be fixed with rigour, what about that one time when you want to use an object as a key? The only way is to consistently use the 1.8 syntax.

In favour of the new syntax

Ok, it’s not all bad I admit. I can think of one place that using the new syntax is better than the old one. For example:

# Ruby 1.8 syntax
before_save :do_awesome, :if => -> { its_awesome_time?(Time.now) }
# Ruby 1.9 syntax
before_save :do_awesome, if: -> { its_awesome_time?(Time.now) }

Excuse the contrived example, but the stabby lambda syntax, also introduced in Ruby 1.9, looks a bit silly when used with the old hash syntax and works nicely with the new one. Of course, in Ruby 1.8 we would have just:

# Ruby 1.8 syntax
before_save :do_awesome, :if => lambda { awesome_time?(Time.now) }

Which looks fine again.

Am I wrong?

There seems to be plenty of support for the new syntax. Even some of my colleagues at Mint jumped straight on the new syntax as soon as we started a project on 1.9. I still don’t get it.

Someone please tell me why the hash colon (even that sounds more ridiculous) is better than the hash rocket?

Tagged: , , ,

§ 67 Responses to I don’t like the Ruby 1.9 hash syntax

  • says:

    HI PHIL!

    As promised, my retort:

    I think all of your points mentioned above are valid. However, I think you omis one.

    When I use hashes, 99% of the time I want a symbol (something immutable) as the key. Therefore, in the majority of cases, I find the new hash syntax pleasing. For example, consider initializing a connection to AWS S3 using the popular fog gem. You might do something like this:

    con = Fog::Storage.new(
    provider: ‘AWS’,
    aws_secret_access_key: ‘ABC123’,
    region: ‘eu-west-1’,
    aws_access_key_id: ‘ABC123’
    )

    See how nice and concise that is? It’s almost prose! I’ve used a similar ‘syntax’ in the paragraph above. `retort: “I like symbols as keys”`.

    To comment on a couple of other points raised:

    The new syntax is not the only improvement in Ruby 1.9. In fact one might go far as to say it is a trivial one. Fibers, native Object#tap (rather than using Rail’s implementation) and others are all arguably more useful. Therefore those using the new syntax in gems are not always doing so for “no good reason”.

    As for thinking one can treat the new hash syntax like JavaScript, well I would chalk that up to user error. It’s still a hash (with a symbol as a key) and will behave as such. That it does not use Ruby’s symbol to denote that the key is a hash could arguably be confusing, but then it is a convenience. Making it explicit would result in the old syntax.

    To quote that infalible source of teenage wisdom Road Trip:

    “That’s why they call it a shortcut. If it was easy it would just be the way.”

    Anyway, just a few thoughts. As I mentioned, I think all your points are valid. Wrong, but valid ;)

    • John Hinnegan says:

      I also dislike the new hash syntax. “When I use hashes, 99% of the time I want a symbol (something immutable) as the key. ” is a fallacy, IMHO. In fact, it’s much more I/O friendly to have hashes full of strings. Anyone using rails is probably working with hashes full of strings more than 1% of the time.

      I also don’t like having 2 ‘equivalent’ ways of doing something. Honestly, the old way, even if hard to type for some (*cough*use vi*cough*) was ‘the’ way to create hashes. This is just one more thing people have to learn. This violates ‘simpler is better’ by introducing not only a new format for creating hashes, but also a new way to declare symbols. It’s also creating a need for ‘convention’ among programmers — not that this is bad, but it’s one more bullet point people trying to adhere to a given form need to check.

      • Matt A. says:

        I’m new to Ruby, but isn’t one of its defining design choices “there is no One ‘Right’ Way?” The new syntax is certainly cleaner when you can get away with only symbols, and the old syntax is still there for when you can’t :)

    • fijiaaron says:

      But then you cant use keywords as symbols:

      { if:’keyword’, and:’syntax’, is:1.9 do:not, allow:’it’, for:’symbols’ }

      Those are probably not good examples, but

      class, self, yield, & module are reasonable symbol names.

      Not to mention the ability to use objects as keys.

    • Let’s remember that JSON objects are hashes, all arrays in JavaScript being associative arrays. The similarity between the two syntaxes is valid.

  • Phil Nash says:

    Hi Adam,

    Thanks for your comments. I still don’t understand though. You find the syntax pleasing? Are you saying that the only argument for its existence is how some people find it looks on screen? Is there something wrong with?

    con = Fog::Storage.new(
    :provider => ‘AWS’,
    :aws_secret_access_key => ‘ABC123′,
    :region => ‘eu-west-1′,
    :aws_access_key_id => ‘ABC123′
    )

    I also fail to believe that anyone really believes that typing 2 less characters is a shortcut (not to forget that space in Ruby files is hardly an issue, we’re not trying to send Ruby files over the Internet to end users). And, as I mention in the article, this just causes inconsistency in a codebase.

    Regarding confusion over the way the syntax could be misleading. I disagree that the whole thing is a convenience. For me, it is convenient to see what is in my hash when I build it, not to cause potential confusion later when I try to access it. I don’t see the point in hiding the already simple structure of the hash.

    Finally, I agree, there are more important new features of Ruby 1.9 and if someone writes a Ruby 1.9 only library, then they are at rights to use the new syntax as it will have to be 1.9 compliant anyway. However changing syntax or using it in a situation where Ruby 1.8 users could be using the library too is a bad thing as it would break it for no reason.

    I do appreciate your use of Road Trip, one of my favourite American college films in the post American Pie world. But need I remind you that on taking that shortcut they destroyed their car and had to steal a school bus from a blind girl. Is this really where Ruby should be going?

    • Matt A. says:

      As a brand new rubyist coming from C++/ObjC, the hash rocket is one of the more annoying bits of syntax I’ve run across. It’s a symbol you have to type multiple times in quick succession if you’re building a hash literal of any real size, and requires you to spread your ring and pinky fingers (the pair least willing to stretch, at least for me) completely across the height of your keyboard.

      Once it’s there on the screen, it presents a fair bit of visual noise (as each of the two characters fill up a fair bit of their fixed-width space) with very little gain in info over any single character. Indeed, the first question that ran through my mind when I found out that ‘=>’ separated a key from its value was “hm, why wouldn’t they just use ‘:’?” (Indeed, it seems Objective-C is doing just that in its new NSDictionary literal syntax).

      I *do* agree, however, that there’s a disconnect between `hash = {test: ‘hash’}` and `hash[:test]`. It wouldn’t be immediately apparent why the colon moves between setting and dereferencing, but it’s also not a huge conceptual link to say “post-colon is for set and pre-colon is for dereference”.

      Perhaps it’s just my lack of experience with Ruby so far, but I agree with @Adam that 99% of the time, I want my hash to use something immutable and less noisy, like symbols, and using the new syntax doesn’t make it any harder to “see what is in my hash when I build it”, and it doesn’t really make dereferencing any harder either. For the large majority of times when my keys are only symbols, I certainly like that syntax; I’ll take the more onerous way of using ‘=>’ when the newer method would cause errors or be generally less readable than the earlier.

  • Dean Strelau says:

    While there are some valid points here that I’d like to address, I can’t help but feel like you’re reaching on a few of these.

    First, I can’t believe you honestly ever going to confuse your Javascript and your Ruby just because the hashes look similar. Do you confuse Ruby with Perl because the regexps look the same? Or with Python because you can write `for x in y` in both languages? Sure you may have the occasional trip up (god knows I’ve seen enough errors from forgetting the semi-colon in my PHP), but I can’t take this as a serious talking point.

    Next, you can’t argue against the syntax because it only allows symbol keys and in the next breath criticize as misleading for only allowing access with a symbol key. You can’t have one without the other. Sure you may not know what that syntax does the first time you see it, but it’s a pretty easy rule to learn after that. A small one-time learning curve is justified if it advances the language; otherwise, you’d never be able to introduce anything new. Aside: your example of a Hash with Object key (# => ‘flexible’) is nonsense — that doesn’t work in any version of Ruby, as you can’t reference an Object like that in a hash-literal.

    On to the more valid points. I agree that these are points to consider when using the new syntax, but I don’t think they’re reasons to avoid it totally.

    Backwards compatibility is obviously a big one, and I don’t disagree with you here. If you want code to work in 1.8 and 1.9, there is no question on which syntax to use. If you update your previously working-in-1.8 gem to the new hash syntax just because it’s the new hotness … well, I hope everyone stops using your gem. There is absolutely no reason for that. On the other hand, if you’re writing a new library I see nothing wrong with using the syntax and requiring 1.9. Ruby 1.9.0 was released 25 Dec **2007**. As a community, it’s time to start pushing people away from 1.8.

    In my opinion, the most important issue you raise is the one you tack on to the very end of your list: consistency in style. While complaints of “it only allows Symbol keys” can be buffered by the fact that the hash-rocket is still available, dropping back to that only when necessary means the old construct will quickly start to stand out like a sore thumb. I far prefer the new syntax aesthetically, so I’m not sure this point alone is worth abandoning it for. How often do you construct hash-literals with non-Symbol keys, especially when working in a Rails-like framework? I’d venture not very often. Still, I’m sure I will cringe every time I see a hash-rocket in the middle of my otherwise nice, clean new hashes. If I have one complaint about new syntax it’s that I can’t use it all the time.

    I’m glad you did address at least one positive of the new syntax, but I’m not sure you picked the most important one: passing a Hash into a method as pseudo-named arguments. I would argue that because of Rails’ influence this is by far the most prevalent way to construct a hash-literal today even in non-Rails code. Ruby already provides a construct for dropping the explicit Hash braces when doing this, and the new hash syntax is the next step. Eg, `do_something amazing: true`. Is this a big change? No, but it’s attention to the little things like this that make Ruby such a pleasure to use.

    • Phil Nash says:

      Thanks for your points Dean. Allow me to address them in order:

      I’m not sure I’m going to confuse my languages due to similarities, it is just my feeling that I like the distinction. Obviously there are many crossovers between language syntaxes, however it is the case that Ruby has the hash rocket syntax and I feel comfortable reaching for that when writing Ruby.

      I’m actually not arguing that it’s bad that you can only access the values by symbols, but that since you did not construct the hash using symbols in the first place that it is misleading. Sure, it is a tiny thing to learn, but I don’t like that it is not obvious, as many things in Ruby are.

      Regarding your point about objects as keys: you’re right. you can’t construct a hash like that. That is wrong of me. However the reality remains confusing. Consider the following:

       ruby-1.9.2-p180 :001 > o=Object.new
      ruby-1.9.2-p180 :002 > hash18 = { o => 'object' }
      ruby-1.9.2-p180 :003 > hash19 = { o: 'object' }
      

      The results of this very similar code is very different. hash18 is {#=>"object"} whilst hash19 is {:o=>"object"}.

      In terms of consistency, not only will you have to drop back to using the hash rocket in the case of using non symbol keys, you will also have to use it when building a hash with dynamic keys (perhaps not as far fetched as using non symbol keys). So it will continue to pop up.

      Finally, though it seems to be the biggest argument anyone has for the syntax, I still don’t understand why aesthetics are always cited as important. When did the hash rocket become so ugly people didn’t want to code with it?

  • says:

    On a lighter note, with new hash syntax, you can write a joke like this http://blog.rubyhead.com/2011/06/06/ruby-initializer/

  • jomonjin says:

    I’m with you. Looks like change for change sake… in every instance but your “stabby lambda syntax” example I prefer the 1.8 syntax for clarity and flexibility. In that last example, I prefer the regular 1.8 lambda syntax and so would use the hash-rocket/lambda keyword combo. Heeeyah!

  • says:

    My biggest complaint with the new syntax is that it provides a special syntax, for a specific data type, in a single context. It’s not an “alternate hash syntax” because it doesn’t cover all hash creation (and, in fact, I take issue with the assertion that it covers the vast, vast majority of hash creation).

    When someone asks, “What’s a symbol look like?” what are you going to say? “Well, in almost every single context, *including accessing a hash*, it looks like :this. When you’re creating a hash, it also looks like :this — if you’re doing :this=>’that’, But looks like this: if you’re using the new syntax. Oh, and btw, when your irb console pretty-prints that has, it’s still gonna look like :this=>’that’. And remember to set the value using the key ‘this:’ (or, maybe just ‘this’) but retrieve it using ‘:this’. And don’t you dare try to do something like {1100: ‘eleven-hundred’} because it’ll blow up.”

    If the use case demanding the new syntax is named arguments, then we should have a new syntax for named arguments (automatically creating local-scope variables of the same names as the keys), not try to shoehorn it into a more general data structure. Building a hash and passing arguments are not conceptually the same thing, regardless of how Ruby’s implementation details may push things. Restricting a new syntax to that specific case would not only make more sense, but would open up the possibility of further extensions to the syntax down the road (type hinting? inline validation?) that could take advantages of subsequent advances in the underlying VM technologies.

    I see where it’s easier for the very narrow range of cases it applies to. I’m not convinced it’s a lot more readable, simply because the colon is a very small piece of punctuation. There’s a big difference between ‘this: that’ and ‘this that’ that isn’t captured very well by the difference in how they look. Ditto with ‘This: that’ and ‘This::that.’

    No one is forcing me to use it. But they are forcing me to read it.

    Now get off my lawn!

  • says:

    I agree with you Phil.

    Symbols are unique to the Ruby language. For newcomers it is an important concept to grasp, as they have many benefits over strings, and are used widely in frameworks like Rails.

    But the water is now muddy. You gave the perfect example.

    hash = { test: ‘hash’ }
    # => { :test => ‘hash’ }
    hash[:test]
    # => ‘hash’

    Try explaining why the key in the first line doesn’t look the same as the key in the second line, without just saying “It work’s that way”. What an unnecessary hurdle to put in front of someone learning Ruby.

    I sincerely hope that the syntax is removed from future versions, or cleaned up so that the example above looks more consistent.

    • Stephen Eilert says:

      > Symbols are unique to the Ruby language

      Oh no they are not. I hate to be the smug Lisper here, but Lisp had then since the 60’s. Ruby just borrowed them.

  • alfuken says:

    Typing “shift+:” is just easier than typing “shift+=+>”, try for yourself a dozen of times. Saves a lot of pain if you have a tunnel syndrome.

  • John van Dijk says:

    I like hash rockets better. ‘The new syntax’ It doesn’t even have a name!

  • jemmywu says:

    I agree: disliked the new syntax the moment I saw it. I don’t much like it in Javascript either because it’s just not as immediately visible as ruby 1.8 hashes.

  • Kirk bushell says:

    Despite its merits, syntax changes like this cause problems and is one of the reasons why php can be a real pain to work with. As said previously, there is a trivial gain here for the price that will be paid by all ruby developers.

  • Phil Nash says:

    Thanks for the responses everyone, particularly those that agree with me. I think they are surprising some of my colleagues who disagree with me!

    Joon is right, this isn’t Objective C, but it seems to be trying to head that way. As Dean said, using hashes as psuedo named arguments is something that seems to be being driven by convention in Rails. I like Bill’s point regarding named arguments though, that if that is what we want then it should be a more integrated part of the language, not as a bolt on to hashes

  • says:

    As an historical note, here are the message (and matz’s response) where I made a proposal for the new syntax, back in 2002. It includes rationals.

    http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/38391

    Matz’s response : http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/38402

    • Phil Nash says:

      Thanks for that Jean, the history is certainly interesting (especially as I didn’t know what Ruby was in 2002!).

      There doesn’t seem to be any discussion of consistency in style given the two methods of constructing the hash literal, was that considered anywhere at all? It’s interesting to see that Matz was considering named arguments in functions, did this really win out over that or is that still under consideration too?

  • says:

    I totally agree Phil. The new hash syntax is complete bullshit. What Bill said is spot on. It just confuses the language completely. Symbols look like this everywhere, except in this one case…

    It’s funny, I’ve been working with Scala for the last 8 months and one of the common complaints about it as a language is that it’s too complex. Well, additions to Ruby like this new syntax are giving Scala a run for its money in the complexity department.

  • You’re not the only one. I don’t like it either. Especially now that I know it doesn’t work everywhere. To me it also muddies things up when determining what is a symbol, variable, method, etc. One of the things I liked was that :this was always a symbol. Without the colon it might be a variable it might be a method, but it doesn’t matter to me as long as it returns a result.

    I wouldn’t mind it so much if I could switch completely, but as you’ve shown, you can’t. As another annoyance…

    def foo; “foo”; end;
    h = {foo:’bar’}
    => {:foo=>”bar”}
    h1 = { foo => ‘bar’}
    => {“foo”=>”bar”}

    I don’t know if there’s a way to make methods work as keys with the new syntax, but a couple of guesses I tried failed. Not that that matters. What does matter is to me, ‘foo’ is now ambiguous.

  • says:

    If you don’t like them that’s cool, but I like the new hash syntax for a few, rational reasons:

    It’s shorter. It’s not just two characters shorter it’s two high-cost characters shorter. Equals is a reach and > is a shift and key press therefore both are ‘high-cost” key presses.

    It just looks better. I use Ruby because it is beautiful. Not just in its design but in its implementation. Beauty is in the eye of the beholder though so to each their own.

    It’s easier to read a long hash now since there’s less noise. foo: “bar” is much easier to grok than :foo => “bar” because there is nothing between the two ideas. At least it is for me and if others are using it too I would imagine it is for them as well.

    Because of all of the reasons above it encourages using a named parameter hash which makes reading method calls much, much easier; method calls can be semantic. You aren’t anti-semantic are you? ;p

    • Stephen Eilert says:

      I fixed this “high-cost key presses” thing ages ago on Emacs. Seriously, in most good editors it is trivial to bind the sequence “=>” to some random key.

      Also, I find the hashrocket sexy.

  • says:

    There is a happy medium. Namely:

    When the usage looks like named parameters, use the new syntax.

    In cases where the lookups by key literal (:foo) are close to the Hash definition, use the old syntax so that :foo is used both in both places.

    • John — it’s just like you to always see both sides of the problem. And that is: “wrong”.

      Don’t you think your wish-washy, flip-floppy ambivalence is inappropriate for ruby (and Rails)? Sure, ruby is a beautiful language. But above all, its rich ecosystem of people having strong opinions and stronger language provides and endless stream of enjoyment to those of us who wish to observe flame wars. And learn new bad language!

      namely: “you’re wrong”, your_mother: “wears army boots”, :so_go_back => “java”

      (See, in that last case, the hash rocket strongly implies “to” which is why it is right)

      (In case not obvious to other readers, this is a (lame) attempt at irony, and I am just poking fun at my friend John who is probably the only former English professor that freakin’ rocks at writing goddamned eloquent ruby code.)

      Best argument for new syntax is: forces people off ruby 1.8 because gems will get rewritten.

  • says:

    The syntax looks kinda strange when the value is also a symbol. For example a recent line from a Thor script I just wrote:

    1.9
    method_options radius: :numeric

    1.8
    method_options :radius => :numeric

  • Mark Jaquith says:

    As someone who only dabbles with Ruby, I find the new syntax confusing. One thing I detest in a programming language is referring to something two different ways. Take BASH, for instance:

    FOO='bar'
    echo $FOO
    

    Ugh. Now in Ruby we can have a similar situation:

    foo = { bar: 'I am bar' }
    print foo[bar] # nope
    print foo['bar'] # nope
    print foo[bar:] # nope
    print foo[:bar] # Yep!
    

    Whereas with the old syntax, it is much more obvious:

    foo = { :bar => 'I am bar' }
    print foo[:bar]
    

    In addition to the new syntax being harder to learn per se, there are now two ways to do something, and one of them has a non-obvious handicap. So new users first need to figure out that these things do the same thing, and then they need to learn about the shortcomings of the new way. Add in backwards incompatibility, and this starts to look like a genuinely bad decision.

  • The new Hash syntax really shines when you’re passing a Hash to a method.

    There are situations where i’d never use it, such as to define a Hash, but for calling a method I think it really fits in well.

    It might appear to be inconsistent, but I’ve defined a rule for myself: only use the Ruby 1.9 Hash syntax when invoking methods, and I stick to it. I think that’s consistent.

    The Ruby 1.9 Hash syntax is not trying to replace the Hash rocket syntax, but supplement certain situations(such as method calling) to make the code a lot more readable, but I guess that’s subjective.

  • Avdi Grimm says:

    Funny I keep coming back to Perl lately.

    I like it because it brings back a Perl-ism I missed in the switch to Ruby.

    “But wait, Avdi” you may say. “Perl used hashrockets! That’s where Ruby GETS the hashrocket syntax from!”.

    True. But Perl also had a constrained Hash type: keys were always strings. Period. This meant it was possible to implement a handy syntax shortcut: For simple keys withotu spaces or funny characters, it would just assume the quotes for you:

    my $h = { foo => 1, bar => 2 };

    Ruby can’t do this, because (as you note), Hash keys can be anything. So keys always require one or two extra characters over the Perl equivalent. This was always a minor annoyance.

    If Ruby Hashes have a “native” key type it’s the Symbol, since we use symbols for them more often than not. I’m glad that after all these years, I once again have sugar for writing common Hash types; sugar that actually manages to be *more* concise than Perl by also shaving a character off of the delimiter.

    That it reflects Javascript as well as being a more natural keyword-argument syntax: well, that’s just gravy.

  • fabianosoriani says:

    I can tell you why it is BETTER in cases such as Adam described:

    For EACH PAIR, you type 2 characters less; elaborating..
    less space_key, : instead of =, less >

    Hasn’t always been the point in Ruby, to be more expressive typing less; or at least, something close to human language?

    I’d go even further with the shortcuts and add another one for :key “value”
    {
    foo:\ look at me, I am a String!,
    bar:\ i am another one with interpolation: #{rand}
    }

    That would save me additional 4 keystrokes! –outrageous!

  • Rob McLarty says:

    I think the hash rocket is easier to read amongst large blocks of symbol content (I can easily see what is what because of the clear direction divisions). Although the rocket does take up more precious screen real-estate. Overall, however, I tend to prefer legibility over size, so I prefer the rocket syntax.

  • […] Phil Nash wants to be very clear that he doesn’t like the alternative Ruby 1.9 hash syntax y: 3 as the […]

  • guest says:

    Wayne, I couldn’t agree more. If the value is a symbol, it also add another confusion to the language.

    has_many :syntaxes, _module: :_class

    that colons are so close together that they look like the namespace syntax:

    Module::Class

    • guest says:

      Add more obvious example:

      def calculate(input)
      return ‘calculating ‘ + input.class
      end

      $ calculate Math::PI
      => “calculating Float”
      $ calculate Math: :PI
      => “calculating Hash”

  • says:

    Another failing of the 1.9 syntax: If it’s so darn good, it should also be used (when possible) by inspect.

  • PaBLoX says:

    As a new programmer; I started to learn Ruby on 1.9.1… after reading a bit and learning about symbols. I found the new syntax very pleasant to work with. I just learn that keys in hashes are symbols. Period…
    So the issue with:

    hash = { foo: ‘bar’ }
    # => { :foo => ‘bar’ }

    hash[:foo]
    # => { :foo => ‘bar’ }

    It actually doesn’t exist.

    I’m just stating this because a lot of people says that “new syntax is so confusing to newcomers” and well… it isn’t – at least not for every newcomer.

    I agree that maybe for people that already learnt ruby it’s confusing (and unnecesary) though.

  • rfichoke says:

    I also hate the new syntax. I’m surprised at the number of people who like it.

    Here’s an example from Rails that took mental effort to process, but shouldn’t:

    format.json { render json: @config_repo }

    Granted, this isn’t helped by the lack of parentheses. But I think this was more immediately obvious in the old style:

    format.json { render json => @config_repo }

    On the JavaScript point: it’s nice that it looks like JSON. But it won’t /behave/ like JSON:

    ruby-1.9.2-p290 :001 > eval({ this: “that” })
    TypeError: can’t convert Hash into String

    If they really did this just to make a Hash look like object notation, that’s a fail. It’s like putting gull wing doors on a Ford Pinto calling it a Lamborghini.

    Anyway: new syntax–do not want. And don’t get me started on the new SASS syntax…

  • says:

    I was skeptical about the new hash syntax. But I find that it is really much clearer when a hash is being used as named parameters. Also, it takes up 3 fewer characters per element. That’s not trivial when you’re doing something like

    my_method param1: value1, param2: value2, param3: value3

    As for making symbols look weird…well, perhaps it does a little, but note that you have the colon in either case. Thus, :this is a symbol, and so is this: . The colon is still there, just more flexible.

    Yes, it’s about aesthetics. Lots of Ruby syntax is about aesthetics.

  • blij says:

    I agree and I prefer to using hash rocket.

  • jaequery says:

    I’m a php coder who recently wanted to dive into ruby. But having read this, I don’t think I will anytime soon.

    Personally, I do prefer the hash colon, as it is what I am most familiar with dealing with JSON all the time in javascript.

    But this type of rift/confusion, is really putting me off.

  • says:

    Dropping my two cents. The only reason that I don’t like the new syntax is that one day I’ll have to explain to a new programmer that _sometimes_ a colon on the right makes a symbol and _sometimes_ it doesn’t.

  • Ben Atkin says:

    I’ve griped about this new syntax and written code intended solely for Ruby 1.9 without using it. Glad to see many others (though perhaps not most) are in agreement. The hashrocket is lovely (I’ve liked it ever since I learned Perl) and the argument that javascript literals should easily be converted to ruby doesn’t hold any water.

  • cvshepherd says:

    I would like to comment on two popular arguments here, against the new syntax.

    1. It’s harder to understand / read.

    Well, that’s because it’s a new feature. It’s something new to learn. Ruby is progressing (not just syntax wise). And since nobody is forcing this new syntax on you, that’s a good thing.

    2. Now there’s more than one way to build a hash.

    Come on; That’s the essence of Ruby. There’s more than one way to do things. This is a means of letting you express your intentions more clearly. And I don’t hear people complaining about the fact that there are about a dozen ways to define a method in Ruby.

  • Pedro says:

    So it is just syntactic sugar.
    I thought it was compulsory from your post.
    As with syntactic sugar, use it when it makes the meal taste better and not at any other time. No big deal, is it?

  • Matthew Nguyen says:

    Thank you for your article!

    My first reaction when I saw the new syntax was: “What’s the point? Is it still Ruby?”
    I didn’t understand why people were so enthusiastic about it… Now I know I’m not the only one!

    I just hope that old school syntax will never be deprecated.

  • andrew says:

    well,
    I dislike It too.
    And I find key: :symbol stuff really ugly-looking.
    But if I write a DSL I may expect people to use it like
    setup ‘something’, with: proc{…}, _and: proc{…}

    But honestly I would prefer this way:
    setup ‘something’ do
    with {…}
    _and {…}
    end # =)

  • Ryan Sharp says:

    Bikeshed-o-rama

  • says:

    I like the new syntax more. To me it’s way nicer to type and looks much better. Yes, I agree, it is sometimes annoying having to resort to the old syntax in some cases. But in 99% of the time it makes life much easier…

  • Kool Breeze says:

    Funny, I have been programming for about 20+ years and I like the new syntax. I like how most who have learned a new language in the last 6 years are completely put away with a choice. It’s a sign of your ability to adapt and your mid-term usefulness…(forget long term)…

  • […] I don’t like the Ruby 1.9 hash syntax— A post by Phil Nash from 2011, interesting not only because of his post, but the conversation in the comments. […]

  • Eric S. says:

    I use the 1.9 syntax for named parameters and the 1.8 syntax for other hashes. I think that is more clear. It also makes more sense with Ruby 2.0. Two ways to do something is good if it signifies an intent. Same thing with fail vs raise for exception handling. fail is better for errors and raise is better to re-throw an exception.

  • says:

    Love the new syntax! Short and clean – much nicer looking than the old hash rockets messing up my “legacy” code :). I agree, there are drawbacks. But the advantage of a much nicer typing experience in most cases and a cleaner look by far outweigh the disadvantages in my opinion. Just alone not having to start typing with a : before the key is wonderful. ;-)

  • says:

    Hey! Would you mind if I share your blog with my facebook group?
    There’s a lot of folks that I think would really
    enjoy your content. Please let me know. Many thanks

  • twajjo says:

    I think people should use whatever they want. I don’t go through code that uses the syntactic form I do not prefer and change it to my own preference. Such anality needs professional psychological intervention.

    I prefer rockets. That’s just me, and largely for the reasons Phil points out. I’m sticking with rockets because I do use numbers for keys sometimes and should be allowed to do so. For me, it’s consistency. Rockets work for all cases, when the new syntax does not.

    Some of the arguments on both sides of the case sound more like a religious preference than anything else.

    If you like the new syntax, by all means use it! I’m glad you are comfortable with your “religion”, and I am happy with mine, kindly leave me to it. I’m not converting until I have a compelling reason to (i.e., “heaven” is better over there).

    Remember, the process of conversion is to “continually and bluntly pound your words into a potential convert’s ears until they start dribbling out of his or her mouth” (paraphrasing R.A. Wilson).

  • Mckain says:

    My friend the hash rocket … I really like the hash rocket in hashes too!

Leave a Reply to blij Cancel reply

What’s this?

You are currently reading I don’t like the Ruby 1.9 hash syntax at Logical Friday.

meta

Follow

%d bloggers like this: