Alan Alcesto: Let's Talk Tech

Home

Ruby Hashes vs. JavaScript Objects

11/15/2015

Like Ruby, JavaScrip has ways of storing a collection of data. One way you can store a collection of data in Ruby is through hashes. Hashes use a key and value index that allows you to call on the key to access the value within the hash. You can also create the hash using symbols. The nice thing about storing a collection in a hash is that you don't have to use a number index like you would in arrays, but instead you can use any object type as your index. Similar to hashes in Ruby, in JavaScript you have objects. Objects are containers for named values. These named values are called properties. Objects, like hashes, do not use a number index. Though objects and hashes are very similar, there are differences in their structure and syntax, but rather than telling you, I have listed both an object and hash below. I used the same information on both the hash and object.

//JavaScript Object

//Ruby Hash (symbol index)

Below is an example of how you would access a property within an object and a value within a hash. In the example they will both return "Alan".

//JavaScrip Object

person.firstName

//Ruby Hash (symbol index)

person[:first_name]

As you can see from the examples listed above that they work very similarly. Of course, there are some subtle differences due to the syntax that comes with their respective languages. Both are great ways of containing a collection of data. Hopefully this has been helpful in understanding the similarities and differences between Ruby hashes and JavaScript Objects.