DEV Community

Discussion on: Why avoid Ruby's for .. in?

Collapse
 
andy profile image
Andy Zhao (he/him)

Given this:

banana = { name: "banana", flavor: "sweet", texture: "soft" }
apple = { flavor: "sweet", texture: "crispy" }
grapefruit = { name: "grapefruit", flavor: "sour", texture: "juicy" }

fruit_basket = [banana, apple, grapefruit]

for fruit in fruit_basket
  puts "#{fruit[:name]} is #{fruit[:flavor]}"
end

fruit_basket.each do |fruit|
  puts "#{fruit[:name]} is #{fruit[:flavor]}"
end

I would say, yeah there's not much of a difference in terms of readability.

BUT there is a good reason. Try running this code example:

Basically, for..in loop can redefine things that you didn't intend to, and that can cause problems.

Reference: Tutorials Point - Ruby Loops

Collapse
 
renannobile profile image
Renan Lourençoni Nobile

I'm on mobile right now, when I get a chance I'll run it on my laptop, but knowing that both loops act differently and for in might cause inconstancy is a great point towards each.

Thank you

Collapse
 
johncarroll profile image
John Carroll • Edited

I believe there are use cases for the for .. in syntax right?

So I don't have anything against the for .. in syntax personally, but no, there are no special use cases for it. I mean, I'm sure if you tried you could construct a situation where for might be preferable to .each, but really, it's presence in the language at this point is just vestigial.

I'm not sure I've ever seen it used outside of a tutorial.

I was amused to see that Crystal-lang went so far as to remove it altogether.

Collapse
 
renannobile profile image
Renan Lourençoni Nobile

Hey Andy, I just ran the code and it really makes much more sense to use each method. I believe there are use cases for the for .. in syntax right?

Anyway, thank you for the information.