Andre Leoni Andre Leoni - 23 days ago 4x
Ruby Question

Difference between 'for' and 'each' Iterators on Ruby on Rails

I have some doubts about the diference beetwen 'for' and 'each' Iterators on Ruby on rails.

I have this case, how is the best practice for this?

Def(method) present in the application_helper.rb file:

def milestone_icons
icons = ["", "icon-world", "icon-star-twohdd-o", "icon-users", "icon-notification", "icon-clock", "icon-eye", "icon-like-filled", "icon-credit-card", "icon-bell" ]

Select present in the haml file:

%select.js-select-icons{style: 'width: 50px', name: 'milestone[icon]'}
- for icon in milestone_icons do
%option{value: icon, type: "icon", selected: (@generic.icon == icon)}
= "<i class='#{icon}'></i>".html_safe


Surprisingly the for construct in Ruby is hardly ever used. People tend to prefer the each style iterator or one of its friends like each_with_index or each_with_object as those are significantly more versatile and often perform better.

I'd strongly recommend you use the each method unless you have a very compelling reason.

The differences are somewhat academic, but the big advantage of using each is you're actually interacting with an iterator and you have a lot of ways of using that. You can actually pass through an iterator from one method to another, and you can chain them together to set up the right structure before doing any work.

The real meat here is inside Enumerable where each is the most basic version of this kind of iterator. There are many that are often a much better fit for whatever problem you're trying to solve.

So, yes, for and each are basically the same, but each is better because it's got friends.