David Walden

JavaScript

March 27, 2016

Looping in Ruby vs. Looping in JavaScript

Ruby has a number of easy-to-use methods that allow you iterate through data structures. each, each_index and map are a few examples of built in iterative methods in Ruby. These methods are an efficient and convenient alternative to using a while or for loop to work through arrays and hashes in Ruby.

In Ruby,

            array = [‘x’, ‘y’, ‘z’]
            counter = 0
            while counter < array.length
              puts array[counter]
              counter += 1
            end

            

can also be written as

            array = [‘x’, ‘y’, ‘z’]
            array.each {|value| puts value}
            
This makes for much cleaner and simpler code.

In JavaScript,

            var array = [‘x’, ‘y’, ‘z’];
            var counter = 0;
            while (counter < array.length) {
              console.log(array[counter]);
              counter += 1;
            }
            

can also be written as,

            var array = [‘x’, ‘y’, ‘z’];
            for (var index = 0; index < array.length; index++) {
              console.log(array[index]);
            }
            

While this last block of code is easier to read and more compact than it’s while loop alternative, it’s not as concise as some of the iterative methods available in Ruby. Ruby has a broader range of possibilities when it comes to working through data structures. But whether you’re working in JavaScript or Ruby, you need to find the right balance between simplicity and readability.