Posted By

chrisaiv on 10/21/07


Tagged

ruby loop


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

arcturus
sergeizen
webstic
dustinchilson
concertman


How to iterate through an array in Ruby


 / Published in: Ruby
 

For all of you actionscripters out there, this example is the Ruby equivalent of writing for(i in array){trace(i);} or for(i = 0; i < array.length; i++){trace(i);}

  1. #A. Create an array
  2. names = %w[chris sandy josie billy suzie]
  3.  
  4. #B. Find the length of the array and iterate through it
  5. names.length.times do |i|
  6. puts i.to_s + " " + names[i]
  7. end

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: ed_ruder on December 27, 2007

With the names array already initialized, a more idiomatic iteration would be:

names.eachwithindex { |name, i| puts "#{i} #{name}" }

Posted By: ed_ruder on December 27, 2007

That would be:

names.each_with_index { |name, i| puts "#{i} #{name}" }

Posted By: chrisaiv on March 10, 2008

Thanks for the tip ed!

You need to login to post a comment.