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

A

Aldric Giacomoni

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:0x028cb304@(irb):15>=>5}=>5}

irb(main):017:0> a = {}
=> {}
irb(main):018:0> a[lambda { x } ] = 5
=> 5
irb(main):019:0> a
=> {#<Proc:0x028c2a4c@(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?
 
A

Aldric Giacomoni

Josh said:
It means that the key is a hash table which contains a key of the
lambda,
that maps to the value of 5. Notice all three sets of code are the same,
the
keys just get progressively more complicated looking. But if you didn't
know
what they were, and just considered them to be an object (which they
are),
then they are no longer so complicated, just complicated looking.
Hah! That makes perfect sense. I know what I'm doing next time I see a
code obfuscation contest.

Thanks!
 
B

Brian Candler

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

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}
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top