DEV Community

salcasta
salcasta

Posted on

Ruby Basics - Loops & Iterators

Let's jump into loops!

Incremental Change

instead of writing

score = score + 1
Enter fullscreen mode Exit fullscreen mode

use the += notation accomplishes the same task

+=
-=
*=
/=
all work

counter += 1
Enter fullscreen mode Exit fullscreen mode

Loops

While loop - while a certain condition is true, it will continue to loop through your code until the condition is false

counter = 1
while counter < 11
  puts counter
  counter = counter + 1
end
Enter fullscreen mode Exit fullscreen mode

Until loop - very similar to the while loop it runs your code until a certain condition is met

counter = 1
until counter > 10
  puts counter
  # Add code to update 'counter' here!
  counter +=1
end
Enter fullscreen mode Exit fullscreen mode

For loop - used when you know an exact number of times you want to run a loop. This is the most commonly used of all the loops

for i in 1..20
  puts i
end
Enter fullscreen mode Exit fullscreen mode

Iterators

.each - will run some code for each item in an array

array = [1,2,3,4,5]

array.each do |x|
  x += 10
  print "#{x}"
end
Enter fullscreen mode Exit fullscreen mode

.times - good for repeating a piece of code a certain amount of times

5.times {print 'Hello World '}
Enter fullscreen mode Exit fullscreen mode

These are just a taste of many iterators available in ruby!

Mini Project

A fun small project is to redact a certain word from a group of text

puts "Enter some text: "
text = gets.chomp

puts "Enter words to redact: "
redact = gets.chomp

words = text.split(" ")
words.each { |word| 
  if word == redact
    print "REDACTED "
  else
        print word + " "
  end }

=begin
Output:
Enter some text: 

Patrick didn't want to go. The fact that she was insisting they must go made him want to go even less. He had no desire to make small talk with strangers he would never again see just to be polite. But she insisted that Patrick go, and she would soon find out that this would be the biggest mistake she could make in their relationship.

Enter words to redact: to

Patrick didn't want REDACTED go. The fact that she was insisting they must go made him want REDACTED go even less. He had no desire REDACTED make small talk with strangers he would never again see just REDACTED be polite. But she insisted that Patrick go, and she would soon find out that this would be the biggest mistake she could make in their relationship.
=end 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)