Ruby Loops and Iterators
Published: 2024-01-24 01:49:07

_Codecademy Cheatsheet_

**Ruby while Loop**

Putting a block of code in a while loop in Ruby will cause the code to repeatedly run the code as long as its condition is true.

If the block of code doesn’t have a way for the condition to be changed to false, the while loop will continue forever and cause an error.

```
i = 1

while i <= 3 do
  puts "Message number #{i}"
  i = i + 1
end

# Output:
# Message number 1
# Message number 2
# Message number 3

```
---

**The 'Until' Loop**

Putting a block of code inside an `until` loop in Ruby will cause the code to run as long as its condition remains `false`. It’s only when the condition becomes `true` that the loop stops.

If the block of code doesn’t allow for a way for the condition to be changed to `true` then the loop will continue forever and it will cause an error.:

```
i = 0
until i == 6
  i = i + 1
end
puts i

```

---
**Ruby Assignment Operators**

Assignment operators in Ruby are used to assign or update values to variables. The most common assignment operator is `=` but others also exist, like `+=`, `-=`, `*=` and `/=`.

```
a = 1;
a += 3;
puts a; # Output: 4

b = 4;
b -= 2;
puts b; # Output: 2

num = 12;
num *= 2;
puts num; # Output: 24

num /= 4;
puts num; # Output: 6
```

---
**Ruby for Loop**

A block of code can be repeated a set amount of times with the `for` loop in Ruby.

```
for i in 1..3 do
  puts "Message number #{i}"
end

# Output
# Message number 1
# Message number 2
# Message number 3

```
_Inclusive and Exclusive Ranges_

`for num in 1...10`. What this says to Ruby is: “For the variable `num` in the range `1` to `10`, do the following.” The following was to puts `"#{num}"`, so as `num` took on the values of 1 to 9, one at a time, those values were printed to the console.

The reason this program counted to 9 and not 10 was that we used three dots in the range; this tells Ruby to exclude the final number in the count: `for num in 1...10` means “go up to but don’t include 10.” If we use two dots, e.g. `for num in 1..10`, this tells Ruby to include the highest number (`10`) in the range.

---
**Ruby loop**

A `loop` method can be used to run a block of code repeatedly in Ruby. Either use curly braces (`{}`) or the `do/end` keyword combination to wrap the block of code that will be looped.

_iterator_
An iterator is just a Ruby method that repeatedly invokes a block of code. The code block is just the bit that contains the instructions to be repeated, and those instructions can be just about anything you like!

```
num = 1
loop do
  puts "We are in the loop!"
  num += 1
  break if num > 3
end

puts "We have exited the loop!"

# Output
# We are in the loop!
# We are in the loop!
# We are in the loop!
# We have exited the loop!

```
The `break` keyword is our Get Out of Jail Free card: it breaks a loop as soon as its condition is met.

---
**Next!**
In Ruby, the `next` keyword is used within a loop to pass over certain elements and skip to the following iteration. It is useful for omitting elements that you do not wish to have iterated. `next` is followed by an `if` statement which defines which elements are to be skipped.

```
for i in 1..5
  next if i % 2 == 0
  print i
end
```

```
i = 20
loop do
  i -= 1
  next if i % 2 == 1
  print "#{i}"
  break if i <= 0
end
```

---
**array**

```
my_array = [1,2,3,4,5]
```

---
**Ruby each Method**

To iterate over an array in Ruby, use the `.each `method. It is preferred over a `for` loop as it is guaranteed to iterate through each element of an array.

```
object.each { |item| 
  # Do something 
}
```
You can also use the `do` keyword instead of `{}`:
```
object.each do |item| 
  # Do something 
end

```

```
data = [3, 6, 9, 12]

data.each do |num|
  puts "The number is: #{num}"
end

# Output:
# The number is: 3
# The number is: 6
# The number is: 9
# The number is: 12
```
---
**The .times Iterator**
The .times method is like a super compact for loop: it can perform a task on each item in an object a specified number of times.

For example, if we wanted to print out "Chunky bacon!" ten times, we might type

```
10.times { print "Chunky bacon!" }

```

---
_Examples:_

```
i = 1
while i <= 50
  print i
  i -= 1
end

```
```
i = 1
until i == 50 do
print i
i += 1
end
```

```
for i in 1..50
print i 
i += 1
end
```

```
m = 0
loop do 
m += 1
print "Ruby!"
break if m >= 30
end
```

```
puts "Text to search through: "
text = gets.chomp
puts "Word to redact: "
redact = gets.chomp

words = text.split(" ")

words.each do |word|
  if word != redact
    print word + " "
  else
    print "REDACTED "
  end
end
```