Sunday, 2 February 2014

How To Iterate Through A Ruby Array

Okay in our last post we talked about creating a simple array using the ruby programming language. In this next little bite sized code example I'm going to show you how to iterate through each element of the array.

First off go ahead and fire up irb, Ruby's interactive environment. In Linux go ahead and open a shell and type in irb, if you're in Windows open the dos prompt and type in irb.

Go ahead and create the array.

 friends = ['dave','pete','paul']

Then type in the following:

friends.each{|friends| puts friends}

Hit enter and the above code iterate through the array and print out its contents like so...


However, if you want the contents of your Ruby array to be printed out in a line rather than list style use the 'print' command rather than 'puts'.

No comments:

Post a Comment