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 Working With Blocks Block Method Practice: Custom Classes

What am I doing wrong?

Challenge: Call the run method on the benchmarker object and pass it two arguments. The first argument should be a string of the description. The second argument can be a block with any code you choose.

class SimpleBenchmarker
  def run(description, &block)
    start_time = Time.now
    end_time = Time.now
    elapsed = end_time - start_time

    puts "\n#{description} results"
    puts "Elapsed time: #{elapsed} seconds"

benchmarker = SimpleBenchmarker.new
benchmarker.run "Something" { puts "This is a block." }

I don't understand what I am doing wrong here.

1 Answer

I found out why I was wrong.

When the run method has only one argument like so:

Class Benchmarker
  def run(&block)
    # do something

then, this is valid ruby:

benchmarker.run { puts "This is block." }

But, when the method has 2 arguments like so:

Class Benchmarker
  def run(description, &block)
    # do something

then, one has to use the do...end syntax to pass the block like so:

benchmarker.run "This is a description." do
  puts "This is block."

Namely, one cannot pass {} as an argument in a method ().


run("fast", {puts "today"})

is invalid syntax.

That's why blocks are passed as &block

My mistake was that I assumed {} and do...end are ALWAYS interchangeable.

I guess this is an exception.

I am posting here so that it might be helpful to others.

Thank you!

Dusty Longwell
Dusty Longwell
6,981 Points

Very helpful!! I was confused as to why it would not work also. I don't think the use of & was described very well in the video.