Ruby/JavaScript Loops Cheat Sheet

This cheat sheet compares equivalent Ruby and JavaScript looping concepts.

Ruby JavaScript
While
--------------

i = 0

while i < 5  do
   puts("Inside the loop i = #{i}" )
   i +=1
end
While
--------------

var i = 0

while (i < 5) {
    console.log("Inside the loop i = " + i);
    i++
}
While/Begin
-------------------

puts("Inside the loop i = #{i}" )
   i +=1
end while i < 5


Do/While
--------------

while (i < 5) {
    console.log("Inside the loop i = " + i);
    i++
}

Until
--------------

until i > num  do
   puts("Inside the loop i = #{i}" )
   i +=1;
end
N/A
--------------






Until/Begin
-------------------

begin
   puts("Inside the loop i = #{i}" )
   i +=1;
end until i > num
N/A
--------------






For/In
--------------

beatles = ["John","Paul","George","Ringo"]

for i in beatles
   puts "#{i} is a Beatle."
end
For/In
--------------

var beatles = ["John","Paul","George","Ringo"];

for (i in beatles) {
    console.log(beatles[i] + " is a Beatle.");
}
.each
-------------------

beatles.each do |i|
   puts "#{i} is a Beatle."
end
For
--------------

for (i = 0; i < beatles.length; i++) {
    console.log(beatles[i] + " is a Beatle.");
}
Break
--------------

(0..5).each do |i|
   if i > 2
      break
   end
   puts "Value of local variable is #{i}"
end
Break
--------------

for (i = 0; i < 5; i++) {
    if (i > 2) break;
    console.log("Value of local variable is " + i);
}


Next
-------------------

(0..5).each do |i|
   if i < 2
      next
   end
   puts "Value of local variable is #{i}"
end
Continue
--------------

for (i = 0; i <= 5; i++) {
    if (i < 2) continue;
    console.log("Value of local variable is " + i);
}


Case
-------------------

grade = "B"

case grade
when "A"
  puts "Well done!"
when "B"
  puts "Try harder!"
when "C","D","F"
  puts "You need help!!!"
else
  puts "You're just making it up!"
end




Switch
--------------

switch (grade) {
    case "A":
        console.log("Well Done!");
        break;
    case "B":
        console.log("Try harder!");
        break;
    case "C":
    case "D":
    case "F":
        console.log("You need help!!!");
        break;
    default:
        console.log("You're just making it up!");
        break;
}