As programming languages, Ruby and JavaScript are very different from another. They may be able to perform many of the same things, but they are optimal for different uses. JavaScript, for example, is a browser- based language that is useful for the client side. Ruby, on the other hand, is more well suited for the server side. This is probably why Ruby offers many more options for iteration compared to JavaScript. After all, looping isn't very necessary on the browser end.
Here is a list of ways to loop in Ruby:
And, here is a list for JavaScript:
As you can see, there are quite many ways to create loops in Ruby. The while statement creates a loop by executing code while a conditional is true:
i = 0
while i < 5
p “While looping in Ruby!”
i += 1
end
You can see above that the code prints "While looping in Ruby!" while the counter variable we set, i, is less than 5. As long as that is true, i will count up and every time it does, print the statement. An until loop will iterate until a conditional is true and a for loop executes code once for each element in an expression.
Ruby also has several built-in methods that are great for creating loops. The #times method is useful for simply repeating a code a several number of times:
5.times {p “Hello!”}
> Hello!
Hello!
Hello!
Hello!
Hello!
Ruby's each and each_with_index methods are useful for looping through data structures.
array = [ "Eunice", "Sam", "Sarah" ]
array.each do |x|
puts x
end
> Eunice
Sam
Sarah
The each method above goes through each element in the array, which is a name, and puts it on the screen. Each_with_index performs the same thing, except you can also access the index.
In JavaScript, there are for loops and while loops. The while loops work just the way they do in Ruby, but the syntax is different. Here, we print a statement while the condition (num <= 5) is true:
var num = 1;
while (num <= 5) {
console.log(“While looping in JavaScript!”);
n += 1
}
For loops in JavaScript loops through a code block a number of times. They take 3 statements:
for(1 ; 2 ; 3) {
code to execute
}
for (var i = 0; i < 5; i++) {
console.log("For looping in JavaScript!")
}
The code block above will print "For looping in JavaScript!" 5 times, once for every loop, while i is less than 5. i will increase by 1 after each loop, eventually leading to the condition being false and no longer executing the code.
As you can see, looping in Ruby mostly differs from looping in JavaScript in terms of the syntax. Ruby also has built in methods that JavaScript does not have. Overall, both langauges can be used to create powerful loops. I hope this gave you some basic knowledge on the two!