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 Yielding Self

Jason Woo
Jason Woo
11,730 Points

Bug? This should work

this runs an error

monster.rb
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 if block_given?
  end
end

monster = Monster.new("Fluffy")
monster.scream { puts "BOO!" }

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

You're close, but the directions sat to "modify the yield statement to send the monster instance to a block..." I won't give the whole challenge away, but you need to pass an argument to yield. (Reply if you have trouble figuring out which argument.)

Jason Woo
Jason Woo
11,730 Points

I added the 'self' argument which worked. I'm not quite sure why it doesn't work without it though. The block doesn't ask or the argument.

How would the code look in order for a yield without the argument as I've written above to work?

Jay McGavren
Jay McGavren
Treehouse Teacher

Your original code, yield if block_given?, would yield to the block without passing the block an argument. Even if you do provide an argument to yield, the block you provide will ignore it if the block doesn't have a parameter. (Ruby requires that the number of arguments in a method call match the number of method parameters, but it's less strict about the number of arguments to yield and the number of block parameters.)