From: "David A. Black" Date: 2005-03-31T04:38:07+09:00 Subject: Re: beginner iterators question Hi -- On Thu, 31 Mar 2005, Jeff Fry wrote: > Hi, > > I am brand new to ruby and liking it so far - particularly the watir test > libraries. Welcome :-) > I am comfortable with the Java for loop syntax (i=0, i<4, i++) and > haven't found something in ruby that feels as elegant, particularly when I > want to use an increasing value i within the loop. Here's an example (with my > limited ruby) > > i=0 > 0.upto(3) do puts 'try number > ' + i.to_s i = i+1 # is > there a more elegant way to do i++ ? > end > > I am guessing that ruby provides a more elegant way to do the above. I would > love recommendations both on how to iterate when I want to use the changing > value of the iterator in the loop, and how in ruby to do i++. Is there a way > with upto() to use the current value during iteration? or another iterator > where that is possible without needing to define i seperately? You need to pass an argument to your code block: 0.upto(3) do |i| puts "try number #{i}" end or you could do: 4.times {|i| puts "try number #{i}" } # here I've used the {} block # syntax, which is pretty # common for same-line blocks or even: puts (0..3).map {|i| "try number #{i}" } (iterating over a range, which you can do if the range uses integral values) For general-purpose incrementing, there's: i += 1 (There's no ++ in Ruby because numbers are immediate values. So this: i = 0 i++ would actually be the same as: 0++ which would cause all sorts of trouble :-) David -- David A. Black dblack@wobblini.net