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

Rob Munoz
PLUS
Rob Munoz
Courses Plus Student 586 Points

Pass Blocks as Args

Hi, I'm struggling to complete this exercise. I was wondering if anybody could elaborate on how I might pass either M or J as an argument.

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 

def M
  puts "abcd"
end

J = [1,2,3,4,5].each {|x| puts x}

benchmarker.run ("a string", J)

3 Answers

Hi Rob,

You will find two arguments inside def run on second line, you may notice.

First is description and second is &block

  def run(description, &block)

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.

#First argument should have "string of description"
benchmarker.run "Any description you want" do

#Second argument should have anything in block
  10.times do
    puts "any code you choose"
  end

end

Here's fully explanation, let's look at 5:14

Please remember, don't add any extra codes and just follow the questions in order to pass the exercise.

Hope that helps. ;)

Hi Rob,

In your code, neither M or J are blocks. M is a method, and J is an array which was generated with the help of a block.

As it turns out, blocks cannot be stored directly in variables, so you will need to directly include a block along with your call to the run method. The syntax for that, as noted by Salmon, is:

benchmarker.run "Any description" do
 # anything here is inside your new block
end
Rob Munoz
PLUS
Rob Munoz
Courses Plus Student 586 Points

Awesome, thanks so much to the both of you. I still don't quite understand the methodology or syntax of passing a block but I made my own example and it worked. I guess I'm a sucker for parentheses. Some of the visual structure is lost when you don't delimit a second argument by a comma or contain it within a parentheses.