Ruby Ruby Blocks Blocks Practice Build a Monster Class: Part 2

Roland Cedo
Roland Cedo
21,261 Points

Why use symbols instead of string keys in this case?

So Jason creates the class "Monster", initializes it with an instance variable called "actions" that is a hash with the key "scream" and value 0.

class Monster 
    attr_reader :name, :actions

    def initialize(name)
        @name = name
        @actions = {
                scream: 0
        }
    end

    def say_something(&block)
        block.call
    end

    def scream(&block)
        actions[:scream] += 1
        print "#{name} screams!"
        yield()
    end

end

Now, in the method "scream", he has to access the instance variable "scream" as a symbol so he can increment the instance variable's value:

    def scream(&block)
        actions[:scream] += 1
        print "#{name} screams!"
        yield()
    end

Can someone clarify why he chose to create "scream" as a symbol instead of a string key/value pairing like:

 @actions = { "scream" => 0}

It is currently my understanding that you should use symbols when you want to have an immutable value in your object, correct? If so why use a symbol when we want to increment the value of scream when we call the method "scream"?

1 Answer

rowend rowend
rowend rowend
2,923 Points

Hi. He uses a symbol because it is more efficient in memory. Side note: when you use symbols inside of a hash you can change the values.