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 Foundations Blocks Examples

Why are brackets not needed here?

Please check out my notes in the code:

class SimpleBenchmarker
    def self.go(how_many=1, &block)
        puts "--------------Benchmarking started------------------"
        start_time = Time.now
        puts "Start Time: \t#{start_time}\n\n"
        how_many.times do |a| #literally "5.times". 5 is sent in as an argument from line 18. a is passed in as a new local variable, but it's not used, but it could be, like 'puts #{a}' would tell you which iteration it is on i.e. 1, 2, 3...etc
            print ". "
            block.call #I think the block is lines 19 and 20
        end
        print "\n\n"
        end_time = Time.now
        puts "End Time:\t#{end_time}\n"
        puts "-------------Benchmarking finished-------------------"
        puts "Result:\t\t#{end_time - start_time} seconds"
    end
end

SimpleBenchmarker.go 5 do #I thought you need brackets () to pass in arguments? The first argument here being '5', and the second one being the block of code?
    time = rand(0.1..1.0)
    sleep time
end

Particularly the last note.

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Brackets are optional in many places in Ruby and Rails. Even if they are, in some cases we write them anyway for readability. I can't really explain where and why exactly - I just do what I often see and got used to it, treat it as convention ;). Do and End are the same thing as { and } - we use braces for single line blocks and do-end for multiliners. More info:

https://github.com/bbatsov/ruby-style-guide#syntax

http://florianhanke.com/blog/2011/12/18/why-i-dont-use-parentheses.html

Cheers