如果仅像某些文章说的前者的效率不如后者,那要前者做什么?
认证0级讲师
Under normal circumstances, try to use each:
each
1.upto(10).each { |i| puts i } puts i # NameError: i is undefined
When using for:
for
for i in 1.upto(10) do puts i end puts i # print 10
It seems there is no difference, there are usually multiple ways to do one thing in ruby
each do is more efficient. Some programming standards generally do not recommend using for in
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
Under normal circumstances, try to use
each
:When using
for
:It seems there is no difference, there are usually multiple ways to do one thing in ruby
each do is more efficient. Some programming standards generally do not recommend using for in
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