0

I found code with hash assignment such as follows:

@defeat = {r: :s, p: :r, s: :p}
# => {:r=>:s, :p=>:r, :s=>:p} 

Why are the keys for this hash generated as symbols? Is this a short form of doing this?

defeat[:r] = :s
defeat[:p] = :r
defeat[:s] = :p

Is there a name for this style of Hash?

slm
  • 15,396
  • 12
  • 109
  • 124

2 Answers2

2

A Hash can be easily created by using its implicit form:

grades = { "Jane Doe" => 10, "Jim Doe" => 6 }

Hashes allow an alternate syntax form when your keys are always symbols. Instead of

options = { :font_size => 10, :font_family => "Arial" }

You could write it as:

options = { font_size: 10, font_family: "Arial" }

Now in your example @defeat = {r: :s, p: :r, s: :p}, all keys are symbol. That's why your example Hash is a valid construct, which has been introduced since 1.9.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Thanks, of course I found the solution right after asking it too: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#Hashes. – slm Oct 07 '14 at 17:15
1

When you use the hash style {key: value} you're actually declaring a symbol for the key. Like Arup's example, {:key => value} is the same thing with the implicit form. So anytime you use : instead of => in a hash, you are creating a symbol as the key.

In your example, you're creating symbols for both your key and your value.

{key: :value } # both are symbols
Eric N
  • 2,136
  • 13
  • 13