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

Andrew Carr
Andrew Carr
10,979 Points

Run function isn't working.

Hey! As it says, I'm supposed to pass in two arguments, first being a string, the second being a block. I've given the block as {10.times (12*13)}

How is my block not working as a callable block?

Thanks!

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 "This is the description of the time" { 100.times (12*12)}
Andrew Carr
Andrew Carr
10,979 Points

follow up: If I chnage the format to

do 
100.times (12*13)
end

it then says challenge one isn't working either. Why is that?

3 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Because your code format is a bit off, but you got most of it right.

benchmarker.run "This is the description of the time" do
  100.times do
    12*12
  end
end

This should do it.

Andrew Carr
Andrew Carr
10,979 Points

So my follow up question is that in the first video of the next exercise Jason uses the code

class Monster
    attr_reader :name
    def initialize(name)
        @name = name
    end
    def say(&block)
        print "#{name} says..."
        yield
    end
end

monster = Monster.new("Fluffy")
monster.say {puts "welcome to my home."}

From here it appears he only needed to put a {} block while in the original challenge I have to make a block which requires something to be done multiple times (10.times do puts "Hello"). How do I know when a block that only asks for one line of code is valid vs when it needs multiple? I can also clarify if it seems my logic is ambiguous.

Thanks!

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

I understand what you mean, it's perfectly ok to write it like this

benchmarker.run "This is the description of the time" do 100.times {12*12} end

One line, and it just works. But I generally write most of my block in do...end for better code readability, and easier to add another line to block body later if I need to.