DEV Community

Felix Imbanga
Felix Imbanga

Posted on

Ruby Loops and Iterators

Today I was working on loops and iterators.
I learned that while loops are used while a variable is happening and a until loops is used until a certain condition is met.

Assignment operators I learned include += (add to counter), -= (subtract from counter), *= (multiply by counter), and /= (divide by counter).

For loops are used when we know how many times well be looping
.. is inclusive of the end range
... is up to the number before the end of the range

Iterators are ruby methods that repeatedly involve a block of code. ex loop { print "Hello, world" }
{}'s are interchangeable with the keyword do (open block)
and end (close block)
next --skips over certain steps in the loop
array - list of items between square brackets

.each method
applies and expression to each element of an object, one at a time
I prefer using {} in stead of do and end when using iterators
I did have a question of the difference between x + 10 and x +=10. ASK GPT described it as "both are expressions that deal with numeric values and perform addition, but they have different effects on the variable. It takes the current value of x, adds 10 to it, and then assigns the result back to x. In other words, it updates the value of x by adding 10 to it".

.times iterator
like a compact for loop
I learned that loops need to use do while do is optional for while and until loops.
There are multiple ways to do a task which is a testament to ruby's versatility.

In the ruby 30 times exercise I thought about it as trying to implement a statement which was occurring passively within the loop rather than trying to actively getting ruby to print "RUBY!" 30 times.

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay