Weird hash key: what am I asking Ruby to do?

Discussion in 'Ruby' started by Aldric Giacomoni, Mar 31, 2010.

  1. I decided to type the following in irb:
    irb(main):010:0> a = {}
    => {}
    irb(main):015:0> a[lambda { x } => 5] = 5
    => 5
    irb(main):016:0> a
    => {{#<Proc:[email protected](irb):15>=>5}=>5}

    irb(main):017:0> a = {}
    => {}
    irb(main):018:0> a[lambda { x } ] = 5
    => 5
    irb(main):019:0> a
    => {#<Proc:[email protected](irb):18>=>5}

    So.. In the first example, the hash key is 'lambda { x } => 5' .
    What on earth does that even mean?

    In the second one, the hash key is a lambda. Does that even serve any
    purpose beyond just being the key for whatever value I choose to
    associate with it?
     
    Aldric Giacomoni, Mar 31, 2010
    #1
    1. Advertisements

  2. Hah! That makes perfect sense. I know what I'm doing next time I see a
    code obfuscation contest.

    Thanks!
     
    Aldric Giacomoni, Apr 1, 2010
    #2
    1. Advertisements

  3. You can omit the hash braces in the last arg of a method call, i.e.

    fn(a=>b, c=>d) is short for fn({a=>b, c=>d})

    foo[bar] is also a method call. It's short for foo.[](bar)

    irb(main):001:0> h = {}
    => {}
    irb(main):002:0> h[1=>2] = 3
    => 3
    irb(main):003:0> h
    => {{1=>2}=>3}
     
    Brian Candler, Apr 1, 2010
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.