Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Blocks Blocks Practice Running Code Before Executing Blocks

Query instance variable in Ruby blocks

In the following example.....

class Monster attr_reader :name, :actions

def initialize(name) @name = name @actions = { screams: 0, scares: 0, runs: 0, hides: 0 } end

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

end

end

monster = Monster.new("Fluffy")

monster.scream { puts "BOO!" }

I thought that if you state at the beginning- attr_reader :name, :actions

you would not have to use @actions again. However in the def scream method, it is referenced. Please could someone explain why.

Thanks, Sara

2 Answers

Seth Reece
Seth Reece
32,867 Points

Hi Sara,

Using attr_reader means that you do not have to use @, but does not make it that you can't. e.g. Both of these will pass the challenge:

class Monster
  attr_reader :name, :actions

  def initialize(name)
    @name = name
    @actions = {
      screams: 0,
      scares: 0,
      runs: 0,
      hides: 0
    }
  end

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

  end

end

monster = Monster.new("Fluffy")

monster.scream { puts "BOO!" }
class Monster
  attr_reader :name, :actions

  def initialize(name)
    @name = name
    @actions = {
      screams: 0,
      scares: 0,
      runs: 0,
      hides: 0
    }
  end

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

  end

end

monster = Monster.new("Fluffy")

monster.scream { puts "BOO!" }

thank you!