Object Colons and Hash Rockets

An object, also known as a hash or associative arrays in other programming languages, is a way to store data structures in a key and value pair. More specifically, we will be taking a look at object literals in JavaScript and Ruby.

The key is an identifier, or a way to access or call your value. And the value can typically be any string, boolean, number, array or another object.

Let's first demonstrate how to write an empty object literal in both languages.

JavaScript

var obj = {};

Ruby

obj = {}

Pretty simple so far.

The master key

Now that we've kicked the tires a little bit, let's dive in a little deeper by adding a key with an empty string value.

JavaScript

var obj = {
  'key': ''
};

Ruby

obj_1 = {
  :key => ''
}

obj_2 = {
  key: ''
}

obj_3 = {
  'key' => ''
}

In the JavaScript snippet, notice the quotes around the key name. You can forgo the quotes as long as the key name is a valid JavaScript name and also not a reserved word. In my experience, it is best practice to always use quotes when naming a key in JavaScript objects.

Ruby is much more relax in the numerous ways you can write the same object. It is important to note that obj_1 and obj_2 will generate a symbol for the key name and obj_3 will generate a string. Symbols are unique identifiers and far more efficient to use rather than the string alternative.

If the textual content of the object is important, use a String. If the identity of the object is important, use a Symbol.
— Jim Weirich

obj_2 syntax was introduced in Ruby 1.9 -- it looks and feels like a JavaScript object. The only thing worth mentioning is that the hash will render down to this {:key=>""} by the interpreter. Writing your hash in the JavaScript way or the traditional Ruby way is fine and solely your preference.


Now that we've warmed up the engine, let's really take these objects for a spin. Here is what a full fledge object looks like in both languages:

JavaScript

var iceCream = {
  'name': 'Grand Slam Vanilla',
  'scoops': {
    'one': 1,
    'two': 2,
    'three': 3
  },
  'ingredients': [
    'cream',
    'milk',
    'sugar',
    'vanilla'
  ],
  'options': {
    'sprinkles': true,
    'cherryOnTop': false
  }
}

Ruby

ice_cream = {
  name: 'Dark Forest Chocolate',
  scoops: {
    one: 1,
    two: 2,
    three: 3
  },
  ingredients: [
    'chocolate',
    'cream',
    'milk',
    'mint',
    'sugar'
  ],
  options: {
    sprinkles: false,
    cherry_on_top: false
  }
}

There it is -- a complete object and what it would like in both of our languages. We even have nested objects within our original objects.

Accessing values

To access a value from the object's key, it can be called like so:

JavaScript

iceCream['name']
  -> 'Grand Slam Vanilla'

iceCream.name
  -> 'Grand Slam Vanilla'

Ruby

ice_cream[:name]
  -> 'Dark Forest Chocolate'

In JavaScript, you can access the value using the brackets or dot notation styles. The dot notation style is the best practice way to call values for JavaScript. The former is just another way to access the value and maybe a better approach when working with a dynamically generated key.

Ruby uses a bracket style format to call for its value. It is important to write the key as a symbol or string, depending on what you initially used to create the data structure in your hash or else you will get errors.

Ruby does not have a dot notation style unless you transform or create your object using a Struct or OpenStruct. Struct does not allow the ability to add attributes after the object has been created. And OpenStruct only extends the dot notation style one level deep last I checked ice_cream.scoops[:one], where as JavaScript does not have that limitation iceCream.scoops.one

Creating values

Creating values is pretty painless. Let's add another option, fudge, to our ice cream objects. Who doesn't like a little fudge with their ice cream?

JavaScript

iceCream.options.fudge = true;
  -> {sprinkles: true, cherryOnTop: false, fudge: true}

Let's also add fudge as an ingredient in our ingredients array.

iceCream.ingredients.push('fudge');
  -> ['cream', 'milk', 'sugar', 'vanilla', 'fudge']

Ruby

ice_cream[:options][:fudge] = true
  -> {:sprinkles=>false, :cherry_on_top=>false, :fudge=>true}

ice_cream[:ingredients].push('fudge')
  -> ['chocolate', 'cream', 'milk', 'mint', 'sugar', 'fudge']

Conclusion

This is by far just an introduction to working with objects in each of these very expressive languages. Objects can be as simple or complex as you like when creating and manipulating them. I'm a little amazed at just how similar things are when working with objects between JavaScript and Ruby. But I'm not complaining.

Resources

Object Literals in JavaScript
Ruby's Symbols Explained
Introduction to Ruby

Up