2

I have the following simplified code example:

class MyTimerClass
    def timed_execution(&block)
        ...
    end
    def elapsed_time
        ...
        return ...
    end
end

...
t = MyTimerClass.new
t.timed_execution {1000.times {"foo".equal? "foo"}} 
puts "block took #{t.elapsed_time} seconds to run."

What I want to do is print out "executed" on every execution of "foo".equal? "foo". Instead of putting this inside the timed_execution method I want to add it to the passed code block. something like...

t.timed_execution {1000.times {"foo".equal? "foo" puts "executed"}}

which is wrong. I guess what I really want to know is how to have multiple statements within a code block. Really simple question I know...

2 Answers 2

3

You can use do .. end instead of braces. Or you can even separate the statements with a semicolon.

t.timed_execution do
  1000.times do
   "foo".equal? "foo"
    puts "executed"
  end
end

OR

t.timed_execution { 1000.times { "foo".equal? "foo" ; puts "executed" } }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is exactly what I was asking for! :D
0

From the question, it seems that you had the idea that a code block in Ruby should be written on a single line. In fact, code blocks in Ruby can span over multiple lines.

Code blocks in Ruby are created by writing statements inside an opening '{' and an ending '}' or an opening 'do' and an ending 'end'. Arguments to the block go on the same line as the block opening. Example :

# Using 'do' and 'end'. 
5.times do |i|
    puts i
end

# Using '{' and '}'.
5.times { |i|
    puts i
}

The above way of writing code blocks are preferred if you are going to have more than one statement inside the block. If you are sure you are only gonna need a single statement then you can also opt to follow one line block style (many people do I think, I myself personally go for this one for a single statement). Example :

# Using a single line.
5.times { |i| puts i }

It's allowed to put multiple statements inside a single line block with the help of semi-colons to separate statements, also it's okay to use multi-line block for a single statement. But its a good idea to not do the former one for better readability.

Also from my opinion it's better to use '{' and '}' for single line blocks and 'do' and 'end' for multi-line blocks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.