使用`each`而不是`for` -`each`循环

时间:2016-02-16 20:46:01

标签: ruby for-loop foreach

以艰难的方式学习Ruby 要求重写脚本:

    i = 0
    numbers = []

    while i < 6
      puts "At the top i is #{i}"
      numbers.push(i)

      i += 1
      puts "Numbers now: ", numbers
      puts "At the bottom i is #{i}"
    end

    puts "The numbers: "

    numbers.each {|num| puts num}

使用for - 循环和(0 .. 6)范围。我能找到的唯一解决方案是使用for - each构造,作者说要避免这种构造:

    def range_loop(increment, upper_limit)

      numbers = []
      for number in (0...upper_limit)
        puts "The number is : #{number}"
        numbers.push(number)
      end

      puts "The numbers: "

      for number in numbers
        puts number
      end
    end

    range_loop(1, 6)

如何使用each构造编写此脚本?

2 个答案:

答案 0 :(得分:3)

您可以使用Range对象和Enumerable#each方法实现此目标:

(0...6).each do |i|
  #some code here
end

答案 1 :(得分:0)

您也可以使用upto

0.upto(6) {|x| p "The number is #{x}"}