We Recommend

Beginning Ruby: From Novice to Professional Beginning Ruby: From Novice to Professional
Beginning Ruby is a thoroughly contemporary guide for every type of reader wanting to learn Ruby, from novice programmers to web developers to Ruby newcomers. It starts by explaining the principles behind object-oriented programming and within a few chapters builds toward creating a genuine Ruby application.


Posted By

chrisaiv on 10/21/07


Tagged

ruby loop


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

arcturus


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.