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!
file = File.open("some_file.txt","w")
file << "more code"
file.close
Compare it to this nice block alternative:
File.open("some_file.txt","w") { |file| file << "adding new stuff" }
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.
One advantage is that it makes it obvious that those additional actions are initialization actions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With