什么是“针对"?在Ruby中 [英] What is "for" in Ruby
本文介绍了什么是“针对"?在Ruby中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby中:
for i in A do
# some code
end
与:
A.each do |i|
# some code
end
for
不是内核方法:
- 红宝石中的"
for
"到底是什么 - 是否可以使用其他关键字来做类似的事情?
- What exactly is "
for
" in ruby - Is there a way to use other keywords to do similar things?
类似的东西:
total = sum i in I {x[i]}
映射到:
total = I.sum {|i] x[i]}
推荐答案
几乎是语法糖.一个区别是,虽然for
将使用其周围的代码范围,但each
在其块内创建一个单独的范围.比较以下内容:
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
与
(1..3).each do |i|
x = i
end
p x # => undefined local variable or method `x' for main:Object
这篇关于什么是“针对"?在Ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文