【问题标题】:Using `each` rather than `for`-`each` loop使用 `each` 而不是 `for`-`each` 循环
【发布时间】:2016-02-16 20:46:00
【问题描述】:

Learn Ruby the Hard Way 要求重写一个脚本:

    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-loops 和(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 构造编写此脚本?

【问题讨论】:

  • 您的描述自相矛盾。作者虽然声称不使用for,但要求您使用for 重写某些内容,而您得到的结果使用for,是作者告诉您要避免的吗?

标签: ruby for-loop foreach


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你也可以使用upto

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

    【讨论】:

    • 6.times { |x| numbers&lt;&lt;x }。冗余each.
    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2014-10-19
    • 2015-01-02
    • 2012-10-11
    • 1970-01-01
    相关资源
    最近更新 更多