Are blocks in Ruby overused?

ruby, ruby-on-rails

Solution

Flip your question: how is the first version more complicated?

Short answer: in general, no. Blocks serve specific purposes.

IMO the block is more communicative because:

- Everything in the block is related

- Scope is enforced at the language level (no more `t` after the block)

Blocks can also execute code before or after the method's `yield`. For example, a block that yields a file can close the file.

Those added parentheses do not make anything more clear: one of the beauties of Ruby (and similar languages) is that optional parentheses make things seem more declarative, which a table definition is.

Problem

I'm starting to learn Ruby and probably unsuprisingly the hardest thing to wrap my head around is blocks. Looking at some examples of their use some of them just seem unecessary complicated, and almost like someone is trying to obfuscate the code. For example, here's some migration code from Rails: ``` create_table :posts do |t| t.string :name t.string :title t.text :content t.timestamps end ``` Assuming that the t refers to the created table isn't this just the same thing as this?: (added parentheses to make it more clear) ``` t = create_table(:posts) t.string(:name) t.string(:title) t.text(:content) t.timestamps() ``` How is the first version 'better' or more clear?

Original source