0

my program works fine with this hash

hash = 
    {
    'keyone'=> 'valueone',
    'keytwo'=> 'valuetwo',
    'keythree'=> 'valuethree'
    }

but someone pointed out the this notation is old and that now I should use:

  hash = 
        {
        'keyone': 'valueone',
        'keytwo': 'valuetwo',
        'keythree': 'valuethree'
        }

I get this error:

no implicit conversion of nil into String (TypeError)

I only changed the hash notation. Can someone explain what is happening?

Tiago Mateus
  • 61
  • 2
  • 13

3 Answers3

2

In the latter your keys are saved as symbols. So you should refer to them as:

hash[:keyone]

And if symbols are just fine, this is even better

hash = {
  keyone: 'valueone',
  keytwo: 'valuetwo',
  keythree: 'valuethree'
}

But, if you need string keys, you have to stick with the "old" syntax

hash = {
  'keyone' => 'valueone',
  'keytwo' => 'valuetwo',
  'keythree' => 'valuethree'
}
Chivorn Kouch
  • 341
  • 1
  • 12
Ursus
  • 29,643
  • 3
  • 33
  • 50
2

I only changed the hash notation.

No, you didn't. You also changed the type of the key objects from Strings to Symbols.

{ 'key': 'value' }

is not equivalent to

{ 'key' => 'value' }

it is equivalent to

{ :key => 'value' }
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

The new notation uses symbols for keys:

hash = {
    keyone: 'valueone',
    keytwo: 'valuetwo',
    keythree: 'valuethree'
}
puts hash
# {:keyone=>"valueone", :keytwo=>"valuetwo", :keythree=>"valuethree"}

Your code also misses the commas between the items.

axiac
  • 68,258
  • 9
  • 99
  • 134