This post is the first in a series of blog posts about Ruby for Rails beginners. These are specifically for Rails developers who want to solidify their grasp of the Ruby language.
More than a decade ago, I started learning Rails before I knew any Ruby. Rails is written in Ruby of course, so when writing Rails code you are writing Ruby code. But at the beginning, I didn't fully understand how Ruby worked. And that's fine. A lot of people started learning Rails and picked up Ruby along the way.
The "Ruby for Rails" series will help you learn Ruby to make you a better Rails programmer.
In this blog post, we'll talk about blocks. Ruby blocks can be confusing to beginners but it's important that you learn them because you'll keep on using them on your Rails application.
One of the first code you'll see with blocks is with loops.
(1..10).each do |i| puts i end
The block is inside
end. This code displays the numbers 1 to 10. When you read it, it kind of makes sense. From 1 to 10, for each i, puts i. If you have experience with other programming languages, you might think this is just a more complicated way to do loops.
each isn't only for numbers. You can also iterate through an array.
["Alice", "Bob", "Eve"].each do |name| puts name end
This code iterates through each element and prints the name. In Rails, you commonly use each when iterating through your model.
Post.all.each do |post| puts post.title end
Say you have a Post model with a title. When you call
Post.all, you iterate on each of those posts and the value is assigned to
post which is inside
| |. Since
post is a Post object, you can call
post.title inside the block.
The examples so far show that blocks can be used to iterate through some objects. But the iteration is a by product of the
each method. Blocks aren't just for iteration. Here's another common code in Rails.
<%= form_with Post.new do |form| %> <%= form.text_field :title %> <%= form.text_area :body %> <% end %>
<% %> because this code appears on ERB templates.
form_with is used to display an HTML form. Here, we call the
form_with method and passes the
form_with yields an object which we assign to
form. You can use any variable inside
| |. We could have used
f here instead of
In the examples above that used
each, we yield each of the objects we're iterating through. In
form_with, we yield exactly one object which is the FormBuilder associated with the model. Inside the block you can use FormBuilder's methods to generate fields like
All the fields inside the block are captured and displayed inside the HTML
These are just a few examples of blocks. You'll see more when writing Rails code. So don't get blocked out when coding!