I'm learning Ruby and RoR at the moment, and I came across this:
<% for post in @posts %>
in the Rails guide. I'd understood that the idiomatic way to do this in Ruby is with:
<% @posts.each do |post| %>
If there is a difference then what is it? And if there isn't a difference then wouldn't it be better for the Rails people to be pushing proper Ruby idioms (rather than this, which looks more pythonic to me)?
Edit: I've just found two conflicting explanations of this: Tutorials Point says they're the same except "a for loop doesn't create a new scope for local variables", whereas CS.Auckland.ac.NZ says for
is just syntactic sugar for the equivalent .each
.
Edit2: The for ... in
in question was for the index.html.erb
generated in app/views/posts
by script/generate scaffold
. I've done a quick check and that now generates the .each
syntax. I guess that part of the guide was written at an earlier stage of rails development when the scaffold generated for ... in
.
Edit3: I can now confirm that for x in y
was used in Rails 2.2.2, but by 2.3.8 it is using y.each do |x|
. Just so you know.