Is there any reason to do use block initialization, like this:
x = Observer.new do
add_event(foo)
some_other_instance_method_on_observer
self.some_attribute = something
end
instead of initializing attributes using the dot operator on an instance variable like this:
x = Observer.new
x.add_event(foo)
x.some_other_instance_method_on_observer
x.some_attribute = something
The only reason here is to have more concise code(you don’t have to add the instance name before the method call). By using blocks in general you can write very neat, concise and readable code. Some times you can save your code consumers lots of typing and even code logic.
Here is a traditional case!
Compare it to this nice block alternative:
It saved the user from the hassle of having to open and close(personally i keep forgetting this one) the file himself. Instead it made him focus on what he wants.
Try to invest blocks in such situations + when you want to write nice DSLs.