How to Create a for Statement in Ruby
One of the things that makes Ruby preferable to programmers is that it's an object-based language. Programmers can create a for statement in Ruby as a way to visit every object in a collection of objects and do something specific with them, a process commonly know as to "iterate". You can create a for statement with arrays, Range objects or any objects that include the Enumerable module. There are two ways of doing this: by creating a for statement or by creating the equivalent each statement.
Instructions
-
Choose an Object
-
1
Choose an object you want to iterate over.
-
2
Define the desired outcome. What type of object you choose depends on the desired outcome. To count within a specific range you'll need to use a Range object. For example, to count from 1 to 10, use this code:
a = (1..10).
To create a list of items or objects, you will need to use an array object. For example, a list of states would look like this:a=%{Maine Michigan Alaska Florida}. -
Create a For Statement in Ruby
-
3
Compose the for statement. The basic structure is "for object in collection". In the following example "a" is a Range object. In the statement "for i in a" i is a number within the defined range of 1 to 10:
a = (1..10)
for i in a -
4
Pass the for loop a block. The block is the section of code that is to be executed for every element in the collection:
a = (1..10)
for i in a
puts "The number is #{i}"
puts "Two times the number is #{i*2}
end
Create the Equivalent Each Statement
-
5
Use the expression: "collection.each do |object|". The each method is used more commonly than the equivalent "for". It's essentially a for loop in disguise. The expression will visit every object in a and assign it to your variable (object) before running the block.
-
6
Pass a block to the each command. It must be delimited by either "do...end" or "{...}". Use "do...end" if the block will be more than one line long. Use "{...}" if the block will be all on one line. For example:
a = (1..10)
a.each do|i|
puts "The number is #{i}"
puts "Two times the number is #{i*2}"
end
-
1
Tips & Warnings
The each method of creating a for statement is more commonly used, and tends to have better syntax.