2/10 Setting Up: What's wrong with this hash!


#1

This is getting frustrating. The last exercise note that in Ruby 1.9 it was easier to create a hash like this:

my_hash = { one: 1, two: 2, three: 3}

I created a hash with movies:

movies = {
    'The Matrix' : 5,
    'The Artist': 5,
    'The Girl With the Dragon Tattoo': 3,
    'Bladerunner': 4
}

... Yet I'm getting an error:

(ruby):1: syntax error, unexpected ':', expecting tASSOC
    'The Matrix' : 5,
                  ^

So what's going on? Can we NOT use strings when creating hashes?


#2

Hi try to remove the space between Matrix and : like that

'The Matrix': 5,

#3

Tried that as well. I keep getting this

Oops, try again. Did you create a variable called movies?

For the sake of moving on, I'm just going to use the hash rockets, but there is something seriously wrong in this lesson.

I guess after it shows you something you still gotta use the 'old' way of doing things.


#4

Try to remove the " " around all your name of all your film


#5

movies = {
    :'The Matrix' => 5,
    :'The Artist' => 5,
    :'The Girl With the Dragon Tattoo' => 3,
    Bladerunner: 4
}

Note that we can only use the 'rocket' (associative array) notation on keys with whitespace. Single term keys do not get quotes when written as a key value pair containing :. When quotes are used, we must use the rocket:

    :'Bladerunner' => 4

#6

Ok thanks for the replies everyone.

So lesson for today... symbols are NOT strings!! The problem was that by adding quotes, I guess the interpreter thinks that I'm typing strings when I really want to use symbols.

This worked:

movies = {
    The_Matrix: 5,
    The_Artist: 5,
    The_Girl_With_The_Dragon_Tattoo: 3,
    Bladerunner: 4
}

puts "What would you like to do?"
choice = gets.chomp

But the problem is that with these movie titles, there are spaces in between. So now I wonder how I can type a symbol name but have the spaces translate to the output without the underscore.

Have "The Matrix" instead of "The_Matrix" for example. I wonder if \" " would work or just " \ ..." (Backslash and a space.

Any ideas?


#7

Work with the symbols as previously illustrated. Don't resort to arbitrary mutations. DO work with the strings, in quotes when they contain white space, and using associative array notation..


#8

    The Matrix : 4

Invalid.

    'The Matrix' : 4

Invalid

    'The Matrix' => 4

Valid, but not a symbol.

    :'The Matrix' => 4

Valid, and a symbol.


#9

Thanks. Very helpful! Make sense.