Looping in JavaScript and Ruby, and other differences

7.13.2015

As a programmer new to JavaScript, one of the most noticeable differences between JavaScript and Ruby is how they handle loops. To me, while I am more familiar with the JavaScript loop syntax having programmed in Java before, I think Ruby actually feels much more natural and makes more sense intuitively. Looping in Ruby: do loops in ruby just mean execute this code until I tell you to stop. syntax is: loop do /code/ end you can also say n.times do for loop syntax in array is: for i in whatever #code end # Add number to destination if number is less than 4 def array_copy(source) destination = [] for number in source destination << number if number < 4 end return destination end each loops in ruby can be called like this: source.each do |number| destination << number if number < 4 end Looping in JavaScript: for(initializing variable; condition; incrementor){ insert code } while(condition true){ insert code } do{ code }while(condition) Most of the loops are self explanatory, one note though is that the difference between the JavaScript do while loop and the while loop is that the do while loop will always execute at least once. One note that I do want to make that can be a VERY confusing and time consuming difference, is the difference between accesing nested values in hashes/objects in ruby/JavaScript. It can be broken down pretty simply. Accessing nested properties of javascript objects goes pretty well most of the time, but what if you are in a for..in loop running through its properties? Now you are dealing with variable names, and any time you want to be accessing a property with a variable name you must use object[variable_name]. In ruby I sometimes get confused on how to access values in a nested hash, but it is also easy to remember. If you have a key declared with :key or key: then you access the value by saying hash[:key], regardless if the colon comes before or after the key, and if the key is declared with "key", just use hash["key"]. For example: hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}} p hash[:outer][:inner]["almost"][3] Will print "congrats" Another example for arrays: array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]] p array[1][1][2][0] This will print "FORE"