Ruby’s Hash != JavaScript’s Object

Tammy Wong
3 min readMay 13, 2021

--

The only “hash” I’ve ever known before coding bootcamp are:
1. hash browns
2. hash tags
3. as a verb, when you “hash it out” after a long argument.

So what’s a hash in Ruby?
Upon my first exposure to Ruby, I thought of hashes the way objects are defined in JavaScript. They’re a collection of key-value pairs, used to store other objects — much like dictionaries. Hashes are also known as “associative arrays” because each key associates with its value. Its key can be used to look up its corresponding value, just as its value can be used to look up its key. Great! Sounds a whole lot like objects in JavaScript! They must be the same thing. Except, almost everything in Ruby are objects, it’s a bit redundant that I treat hashes like a JavaScript object…if it’s already an object. There has to be more to it.

Syntax:

site used for example below

Ruby hash: movie = {title: “EuroTrip”, year: 2004}
JavaScript object: var movie = {title: “EuroTrip”, year: 2004}
They sure look similar, don’t they? Both use curly brackets, both have values assigned to its respective key. If I didn’t know any better, I’d say they’re the same thing.
Accessing values:
Ruby hash: movie[:title] => “EuroTrip”
JavaScript object: movie.title => “EuroTrip”
Ruby and JavaScript use different notations to access values. JavaScript accepts both bracket and dot notation but Ruby hashes only support bracket notation.

A NoMethodError will occur if dot notation is used because Ruby attributes dot notation with invoking methods — a method called “title” doesn’t exist. The semicolon, also known as a symbol as shown in the above example, acts like a placeholder for hash keys. There can only be one symbol associated with a particular key and cannot be changed once it is defined. Each symbol exists once in memory, so if multiple symbols with the same name are created, only one object will be created. This allows for less consumption in memory and renders faster than keys that are set to strings.
Functionality:
Ruby hashes are versatile and are able to take in any data type or object as keys, but it cannot take in a method as a value — methods are not objects. JavaScript on the other hand, is able to take in functions as a value, but restricts its keys to just the properties of the object.

TLDR; Hashes are similar to JavaScript’s objects but they are not the same.

Hash Cheat Sheet:
- Creating
an empty hash:
Option 1: hash- literal form: { }
Option 2: hash.new
- Deleting a hash: hash.delete
- Updating a hash: hash[:key] = value
- Accessing value:
Using symbol: hash[:key]
Using string: hash[“ ”]
Using integer: hash[num] (don’t confuse this with indexes in arrays!)

--

--