PHP中文网2017-04-21 10:58:48
Under normal circumstances, try to use each
:
1.upto(10).each { |i| puts i } puts i # NameError: i is undefined
When using for
:
for i in 1.upto(10) do puts i end puts i # print 10
阿神2017-04-21 10:58:48
It seems there is no difference, there are usually multiple ways to do one thing in ruby
怪我咯2017-04-21 10:58:48
each do is more efficient. Some programming standards generally do not recommend using for in
PHP中文网2017-04-21 10:58:48
This is a matter of programming style. The each loop is a functional style, and the for loop is an imperative style
each is actually a method on an iterable object, accepting a block as a parameter
for is a loop structure implemented in the grammar