First of all, I realize I should have tried to fully grasp Ruby before jumping into Rails. However, nothing in Ruby seemed too difficult to quickly grasp (until this!), so I decided to get started while I was still enthusiastic about learning. ,__,
Anyway, here is a super-condensed example of form_for:
<%= form_for(@post) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% end %>
I understand that methods in Ruby need not be called with parenthesis. However, form_for is being called with parenthesis, and yet somehow, it seems as though the do |f| block is being passed to it!
Is form_for returning a method that takes a block, and then is that method immediately being called (without parenthesis) by passing the do |f| block? What’s going on here?
Ruby uses a lot of what is called ‘syntactic sugar’ in that it is a bit more flexible than other languages in how certain operations are interpreted.
for instance:
is actually a function call:
your
form_forexample is a similar case. Blocks are silently passed into Ruby functions as a parameter.is equivalent to
and in the function def for
my_functionyou could write:and you could access the block via the parameter, as well as
yield.So when you use block syntax, it’s interpreted as a parameter, but it’s really not.