sdawes
sdawes

Reputation: 661

Using `each` rather than `for`-`each` loop

Learn Ruby the Hard Way asks to rewrite a script:

    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}

using for-loops and the (0 .. 6) range. The only solution I can find to work uses the for-each construct, which the author says to avoid:

    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)

How can I write this script using the each construct?

Upvotes: 1

Views: 87

Answers (2)

Nabeel
Nabeel

Reputation: 2302

You could also use upto

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

Upvotes: 0

Ilya
Ilya

Reputation: 13487

You can use Range object and Enumerable#each method for this goal:

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

Upvotes: 3

Related Questions