Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!