From: Mike Harris Date: 2006-02-22T02:08:03+09:00 Subject: Re: Blocks / Closures Picklegnome wrote: >I've just been looking into Ruby in the last few days, and I must say it >does look promising. However, many of the tutorials and other resources I've >been looking at use blocks. Having done some research, I'm beginning to >understand what they are and how they are used. However, I've only come >across examples that use them for iteration and keeping a static variable >hidden. Is there something I'm missing? Can blocks be used for non-iterative >functions? > > > > > Blocks are great, for all the standard stuff, iterations/list manipulation being the foremost example. Code that would require 15 lines and a new method in Java or C++ requires a 1/2 line block and no additional overhead such as methods. If this was the only thing blocks did, they would still be indespencible. However, there's more. Blocks allow you to express a piece of logic on its own, independant of any other construct. As an example which may or may not help you, I am in the beginning status of a design (for work) to use blocks within metadata to express the business rules of our client. Now, all the business rules are expressed as methods of inline pieces of code. Say our software manages the buying and selling of widgets. Somewhere in the code, there is this method (it's C++): BOOL Widget::IsAvailableForPurchase() { BOOL result = FALSE; if ( !IsBeing Repaired && /* some other conditions */ ) { // some code goes in here that sets result } return result; } And then elsewhere, in a validate function, is this code if (IsBeingSold() && !IsAvailableForPurchase()) { PostError(.........) } Very exciting. Like any toy example, this example doesn't seem so bad. Pretty ugly, but not henious. Multiply by 10000, them multiply by different business rules for 10 different clients, then imagine all the stupid code you have to write to satisfy the compiler, then add in all the non-business-logic code we need to mesh with the guts of the program, then add in code rot on a decade old product. Trust me, it haunts my dreams. The main problems are that the business rules gets mixed in with the rest of the code, and they are expressed in a manner than looks more natural to a programmer than to somebody in the business domain. What I would like to do is, in some file (let's call it BusinessRules.rb) validation_failure "Widget Must Be Available For Purchase To Be Sold" do |widget| widget.being_sold? && !widget.available_for_purchase? end The block should return true if the validation fails. This is ugly, but it's just a toy example. The benefits here are that all your business rules are expressed outside of code and are not sullied by other code. My example sucks. For a better example of this concept and Domain Specific Languages, check out Rake.