Search code examples
rubyhashkeyword-argument

How not to mix hash and keywordArgument in a Ruby function?


    def passingHash(it)
        p it
    end

    def passingKeywordArg(name: 'David', number: 15)
        p name
        p number
    end

    # We actually pass a hash here.
    passingHash(name: "hello", number: 100) # Print {:name=>"hello", :number=>100}

    # These are two arguments.
    passingKeywordArg(name: "hello", number: 100) # Print  "hello"  100

I'm learning Ruby now. I found these two invocations look the same, but their parameters are totally different. Is using => to represent the hash a recommended way here? I looked up into this code style guideline and found => is not recommended to use. Did I misunderstand anything?


Solution

  • The tutorial is not saying that using => (AKA "hash-rocket") is bad, it's saying the use of Strings or other objects besides symbols (:foo) uses more memory.

    { :foo => 'bar' }
    

    is the original way of defining a symbol as a key. Compare these two definitions:

    { :foo => 'bar' } # => {:foo=>"bar"}
    { foo: 'bar' }    # => {:foo=>"bar"}
    

    We tend to use foo: because we're lazy.

    Symbols don't cost as much, but that's a different subject and why can be found with a little searching.

    As developers we need to understand the cost of using one algorithm or object versus another. Using Strings or whatever as a key has its time and place and knowing those can save a lot of memory or development time.

    Finally, style guides are useful; Read several of them periodically and consider what they're suggesting. The guides are aimed at teams to help them write in a common and consistent manner following good coding practices adapted for Ruby, however they're not cast in stone. Knowing why they're recommended is important, because occasionally we have to ignore or bend the rules, but, when we do, we better be ready to explain why in a code-review.

    And, if you're not familiar with Ruby's coding styles, I'd recommend learning about Rubocop, which is a nice tool for checking for consistent and accepted programming style and catching errors.