Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

metaprogramming - What is "for" in Ruby

In Ruby:

for i in A do
    # some code
end

is the same as:

A.each do |i|
   # some code
end

for is not a kernel method:

  • What exactly is "for" in ruby
  • Is there a way to use other keywords to do similar things?

Something like:

 total = sum i in I {x[i]}

mapping to:

 total = I.sum {|i] x[i]}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's almost syntax sugar. One difference is that, while for would use the scope of the code around it, each creates a separate scope within its block. Compare the following:

for i in (1..3)
  x = i
end
p x # => 3

versus

(1..3).each do |i|
  x = i
end
p x # => undefined local variable or method `x' for main:Object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...