Loops in Ruby

Iterative statements are termed as loops; as with any other programming language, loops also exist in Ruby programming. Let's use them and see how their syntax differs from other languages:

def forl(a) 
for i in 0..a 
print("Number #{i}n") 
end 
end 
forl(10) 

The preceding code iterates the loop from 0 to 10, as defined in the range, and consequently prints out the values. Here, we have used #{i} to print the value of the i variable in the print statement. The n keyword specifies a new line. Therefore, every time a variable is printed, it will occupy a new line.

Iterating loops through each loop is also a common practice and is widely used in Metasploit modules. Let's see an example:

def each_example(a) a.each do |i| print i.to_s ...

Get Mastering Metasploit - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.