Header Banner
Null Byte Logo
Null Byte
wonderhowto.mark.png
Cyber Weapons Lab Forum Metasploit Basics Facebook Hacks Password Cracking Top Wi-Fi Adapters Wi-Fi Hacking Linux Basics Mr. Robot Hacks Hack Like a Pro Forensics Recon Social Engineering Networking Basics Antivirus Evasion Spy Tactics MitM Advice from a Hacker

Basics of Ruby: Part Two (Loops)

Aug 16, 2015 08:52 PM
Aug 16, 2015 08:57 PM
Code snippet demonstrating a loop structure in a programming language.

In the last Ruby article, we talked about how to store information in three different kinds of storages: variable, array, and a hash. After we get the data, we have many ways of using them, but, for right now,

we're going to only focus on loops

Loops

Ruby specializes in the concept of being able to do operations in many different ways. That is ever so true for loops. Let's get to it...

1) The "loop" loop

Code snippet demonstrating a loop and execution block in Ruby.

This kind of loop is called with a simple "loop {}" statement. It will continue to execute the block of code inside until it is told to stop. (This will be covered in the Error Handling article coming soon.)

2) Number iteration loop

A lot of times while I'm coding, I have a need to execute a block of code with a number then execute it again with the next number numerically. The number iteration loop makes this a breeze!

Code snippet showing a programming loop with comments.

Note: The two periods in between the numbers means include the last number, while the three periods means include all numbers in between EXCEPT the last number.

3) "each do" loop

After we store data and we need to modify it, you would use the each do loop. For example, say we have an array of numbers and wanted to print the output of all the numbers times three. Your loop would look something like this:

Array manipulation in Ruby code snippet

Simplified down, this means, "For each item in number_array, store the value in V and then print the number multiplied by 3." Very simple right now, but it can get confusing fast. This can also be done with a hash. The only difference is you need two variables.

Code snippet showing a hash in Ruby with key-value pairs for name and age.

Loops are very important in coding. Now that you know about them, mess around with them or try to break them, but try to get comfortable with them, as they aren't going anywhere!

Next up: Basics of Ruby: Part 3 (operators and built-in functions)

You already know how to use your phone. With Gadget Hacks' newsletter, we'll show you how to master it. Each week, we explore features, hidden tools, and advanced settings that give you more control over iOS and Android than most users even know exists.

Sign up for Gadget Hacks Weekly and start unlocking your phone's full potential.

Related Articles

Comments

No Comments Exist

Be the first, drop a comment!