JavaScript & Donuts

Ruby vs JavaScript / Hashes and Objects

February 14, 2016

Alyssa Page

At first glance a Ruby Hash and a JavaScript Object appear to be almost identical. This is especially true if the Object is declared using the Object literal method and symbols are used as keys in Ruby. Let’s create one of each containing the same information to compare.


        #Ruby
        dog  = {
          name: “Lucy”,
          age: 7,
          breed: “Chihuahua”
        }

        #JavaScript
        var dog  = {
          name: “Lucy”,
          age: 7,
          breed: ” Chihuahua”
        };    
      

Initially these look virtually identical and even accessing the information is similar. Let’s access the name information in each.


        #Ruby
        dog[:name]    --> output Lucy

        #JavaScript
        dog.name    --> output Lucy 
      

Ruby uses what are known as key, value pairs in a hash. A key can be any data type (ie strings, symbols, integer, etc) while in JavaScript it is just a property and can only be variables. In out Ruby example we used symbols as the keys.

Both keys and properties can point to any type of object, strings, arrays, integers, etc., even other Hashes or Objects. One difference is that JavaScript Objects can take functions as values so calling a property on an Object can be a function call. So if you are familiar with one, both or neither there are quite a few similarities between the two making easy to compare at times.