February 2, 2004 Intro to Ruby Slide #17
Prev Next

Iterators (continued)

Ruby's standard objects have lots of useful iterator methods...
     0.upto(4) { |x| puts x }

     3.times { puts "Pony!" }

     [10, 20, 30].each { |x| puts x }

     [30, 10, 20].sort { |a, b| b <=> a }

     h = {"dog" => "bark", "cat" => "meow"}
     h.keys.each do |k|
         printf "%s => %s\n", k, h[k]
     end

     ARGF.each do |line|  # like "while (<>)" in Perl
         line.chomp!
         if line.length > 80
             puts line
         end
     end


Prev Copyright © 2004 Walter C. Mankowski Next