How to iterate over an array in Ruby

Array implements an enumerable each which allows you to iterate over an array.

my_array = [1,44,32,’asc’,’ere’]
my_array.each { |item| puts item}

You can use collect method of Enumerable Class if you want to transform an array

my_array.collect { |item| item*3}

In case you want to replace values in an existing array, you can use destructive property of the collect method by adding an exclamation point at the end

 my_array.collect! { |item| item.upcase}

Important to note that an Array class includes Enumerable module. As a result, such methods are each, collect are available for use.

In case you want to get an array element with its corresponding index, you can use Enumerable module method called each_with_index.

my_array.each_with_index do |item, index|
  puts “Value #{item}  with index #{index}
end

In addition to repaying on Enumerable module methods, an Array class implements several generators

my_array.reverse_each {|item| puts item}

There are several other useful generators available in the Ruby for an array class such as .upto, .step. There are other iterators, commonly found in several programming languages, available to use including for, while, until.

Here is a list of examples that help you to see how each of these iterators can be used.

for index in (0…my_array.length)
  puts “Value #{my_array[index]}”
end

while index < my_array.length
  puts “Value #{my_array[index]}”
  index+=1
end

unitl index == my_array.length
  puts “Value #{my_array[index]}”
  index+=1
end

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…