search

Home  >  Q&A  >  body text

ruby中的for in与each do的区别到底是什么?

如果仅像某些文章说的前者的效率不如后者,那要前者做什么?

PHP中文网PHP中文网2774 days ago817

reply all(4)I'll reply

  • PHP中文网

    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

    reply
    0
  • 阿神

    阿神2017-04-21 10:58:48

    It seems there is no difference, there are usually multiple ways to do one thing in ruby

    reply
    0
  • 怪我咯

    怪我咯2017-04-21 10:58:48

    each do is more efficient. Some programming standards generally do not recommend using for in

    reply
    0
  • PHP中文网

    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

    reply
    0
  • Cancelreply