Ruby vs. JavaScript: a first look at data structures
Hash vs. object
July 31st, 2015
Week 7 at Dev Bootcamp was about another object oriented programming language: JavaScript. JavaScript is similar to Ruby in many ways, though their main usage differ, to keep it simple: JavaScript is the reference for software animation and interactivity, whereas Ruby is used as a back-end language. Regardless of their purpose, they both need to store and process data. A few weeks ago we discussed arrays and hashes, this week we will see how Ruby's hashes are very similar to JavaScript's objects.
The Ruby hash
In Ruby, we have 2 main ways to create hashes:
music_implicit_form = { "Michael Jackson" => "Beat it", "Arcade Fire" => "The well and the lighthouse", "Billy Paul" => "Your song", "Drake" => "Know yourself", } music_alternate_form = { Michael_Jackson: "Beat it", Arcade_Fire: "The well and the lighthouse", Billy_Paul: "Your song", Drake: "Know yourself", }
In the first form the keys are strings, but they could be any other kind of object: integer, array and so forth. In the second form the keys are symbols. To add or modify items to either of these forms we can type:
music_implicit_form["2pac"] = "changes" music_alternate_form[:2pac] = "changes"
To display values, we could also do it 2 ways:
puts music_implicit_form["Arcade Fire"] puts music_implicit_form[:Arcade_Fire] # The well and the lighthouse # The well and the lighthouse
The JavaScript object
Objects offer the same features in JavaScript. An object literal is a series of properties, keys in Ruby, and associated values of an object, enclosed in curly braces { }. Here is how it looks:
var music_alternate_form = { michaelJackson: "Beat it", arcadeFire: "The well and the lighthouse", billyPaul: "Your song", Drake: "Know yourself" };
Notice here that an object is also a variable and always to be started with 'var', also the closing curly brace must be followed by a semi-column: yes, JavaScript is tough on syntax. Another important difference is that the keys can be any data type in Ruby, but this is not the case in JavaScript. In JS the properties are considered variables and must follow the required syntax.
To add properties to our JS object or display current values, we would go like this:
console.log(music_alternate_form.arcadeFire); // The well and the lighthouse music_alternate_form.arcadeFire = "In the backseat"; console.log(music_alternate_form.arcadeFire); // In the backseat
Outside of syntax, objects and hashes have remarkably similar features, they can both be modified, printed and stored within a variable. They also feature built-in methods that make our life as developers easier, for more resource on that check out the Ruby Doc and the Mozilla Developer Network. I hope this was useful, happy coding!