Javascript Objects and Ruby Hashes

By on

Javascript objects and Ruby hashes are constructed the same, except that Ruby uses hashrockets =>. Both of them use key and value pairs, in Javascript the key is called property. In Javascript the properties can only be in string form, so if a number is used as a property, Javascript will “stringify” it but if you use special characters make sure there are double quotes around it. Ruby on the other hand can use strings, symbols and numbers as keys.

JavaScript Object:

Ruby Hash:

Accessing Properties in JavaScript:

Here are some of the different ways you can access Javascript object properties.

Accessing Keys in Ruby:

Accessing Values in JavaScript

We can access values in Javascript using dot and bracket notations. Make sure that you use double quotes inside the bracket notation (see line 4).

Make sure that the bracket notation is used inside the loop and not a dot notation (see lines 7-9). See what happens on lines 17 through 25 when the dot notation is used.

In addition to the bracket notation (lines 7-9), notice on line 8 that the word key is not inside double quote marks, this is because it is a variable, the “placeholder” we use in the for..in loop.

Accessing Values in Ruby:

There are different methods in Ruby does the job for us. Line 11 shows you how to access the value of the “Texas” key.