views:

228

answers:

3

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
+4  A: 

One advantage is that it makes it obvious that those additional actions are initialization actions.

Peter
+4  A: 

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.

khelll
+1  A: 

Building on khell's answer, variables created within a block go out of scope outside of the block, which is a good thing if you don't have any more use of it.

Andrew Grimm