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.

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

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

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
  end
end

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
  end
end

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."
end

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

This:

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.