Are there any advantages to using block initialization?

Is there a reason to use block initialization, for example:

x = Observer.new do add_event(foo) some_other_instance_method_on_observer self.some_attribute = something end 

instead of initializing the attributes using the dot operator in the instance variable, like this:

 x = Observer.new x.add_event(foo) x.some_other_instance_method_on_observer x.some_attribute = something 
+4
source share
4 answers

The only reason here is to have more concise code (you do not need to add an instance name before calling the method). Using blocks in general, you can write very neat, concise, and readable code. Several times you can save your code consumers a lot of input and even code logic. Here is a traditional case!

 file = File.open("some_file.txt","w") file << "more code" file.close 

Compare this to this nice block alternative:

 File.open("some_file.txt","w") { |file| file << "adding new stuff" } 

It saved the user from the need to open and close (I personally forgot this) file itself. Instead, he made him focus on what he wanted.

Try investing blocks in such situations + when you want to write beautiful DSLs.

+5
source

One of the advantages is that it makes it obvious that these additional actions are initialization actions.

+4
source

Based on khell's answer, variables created inside the block go beyond the scope of the block, which is good if you no longer use it.

+1
source

If your code is in a method that returns an object. Compare

 def create_observer Observer.new {|x| x.foo, x.bar = calculate_foo, calculate_bar } end def create_observer x = Observer.new x.foo = calculate_foo x.bar = calculate_bar x end 

Thus, using a block can allow you to write logic on a single line. Even if you use parallel assignment in the second example, you still need 3 lines.

Also check out tap here . It has similar advantages.

0
source

All Articles