Byte Friendly

Random thoughts on programming and related topics.

Ruby: for.. In Loop

| Comments

You live to learn every day. Today I discovered for..in loop in ruby. When I saw it in a question on stackoverflow, I was like “Hey, dude, this is ruby, not javascript!” in my head. But, apparently, it’s legal ruby :)

1
2
3
4
5
6
7
8
9
arr = [1, 2, 3]

for a in arr
  puts "element #{a}"
end

#=> element 1
#=> element 2
#=> element 3  

You can put ranges in there also.

1
2
3
for a in (1..10)
  puts a
end

I usually write such loops with .each, but good to know there’s another way.

Comments