Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any advantages in using block initialization?

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
like image 214
uzo Avatar asked Dec 29 '22 15:12

uzo


2 Answers

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.

like image 109
khelll Avatar answered Jan 12 '23 03:01

khelll


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

like image 27
Peter Avatar answered Jan 12 '23 04:01

Peter