Categories
Dev Bootcamp

From Ruby Hashes to JavaScript Object Literals

From the perspective of someone who has a primer on Ruby and jumping onto JavaScript, I noticed something used very often in Ruby that is missing from JavaScript: Ruby Hashes. How can such a powerful data type not exist in other object-oriented languages? If you are also completely new to JavaScript and have the same question, fear not! There is something in JavaScript we can use to achieve the same features provided by Ruby Hashes: JavaScript Object Literals.

MDN defines an object literal as “a list of zero or more pairs of property names and associated values of an object.” As you can see from the definition, this is very similar to Ruby Hash‘s pairs of keys and associated values.

Here is a side-by-side comparison of creating, reading, changing, adding, and deleting a new JavaScript object literal versus a new Ruby hash literal:

JavaScript Object Literal:

//creating new JS object literal
var capitals = { spain: "Madrid",
  france: "Paris",
  italy: "Rome",
  hungary: "Budapest",
  germany: "Berlin"
};

//accessing JavaScript object value
capitals["france"]; //returns "Paris"
capitals["belgium"]; //returns undefined

//changing values
capitals["france"] = "Nice";

//adding a new property/value pair
capitals["russia"] = "Moscow";

//deleting a property/value pair
delete capitals["italy"];

//final result
console.log(capitals);
/*
prints:
{ spain: 'Madrid',
  france: 'Nice',
  hungary: 'Budapest',
  germany: 'Berlin',
  russia: 'Moscow' }
*/
Ruby Hash Literal:

#creating new Ruby Hash literal
capitals = { spain: "Madrid",
  france: "Paris",
  italy: "Rome",
  hungary: "Budapest",
  germany: "Berlin"
}

#accessing Ruby hash value
capitals[:france] #returns "Paris"
capitals[:belgium] # returns nil

#changing values
capitals[:france] = "Nice"

#adding a new key/value pair
capitals[:russia] = "Moscow"

#deleting a key/value pair
capitals.delete(:italy)

#final result
p capitals
=begin
prints:
{:spain=>"Madrid", :france=>"Nice", :hungary=>"Budapest", :germany=>"Berlin", :russia=>"Moscow"}
=end

See how similar they both are? Creating a JavaScript object literal is almost the same as creating a Ruby hash literal. It is important to note that while Ruby hash keys can be any data type (i.e. symbols, strings, integers, hashes, etc.), JavaScript object properties can only be variables. But they can point to any data type value, just like in Ruby hashes.

You can call a JavaScript object’s properties in a similar fashion as you would a Ruby hash‘s keys. Same with creating and deleting key/value and property/value pairs. Calling a non-existent key or property will return nil or undefined.

Note that while I used the bracket notation here to access and modify a JavaScript object’s properties, you can also use a dot notation. For a more in-depth explanation of the differences between the two types of notation, take a look at this medium article.

The next time you find yourself working with JavaScript and are looking to implement something similar to Ruby Hashes into your script, JavaScript object literals will fit the bill perfectly.

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

What Are The Differences Between Ruby Arrays And Hashes, And When To Use Each?

Overview

This is a pretty long blog, so I will seperate this post into three parts:

  1. Arrays
  2. Hashes
  3. Summary

Arrays

1a. What is an Array?

Do you find yourself assigning way too many variables to different values? Arrays are the solution to that.

A array is a list of objects (strings, numbers, booleans, another array, etc.). Every slot in an array acts like a variable.

Examples:

['Hello','World']
['My','name','is','tony']
[17.0,'male',true]

1b. How do I create an Array?

One way to create an array is to put the values you want to store in a set of brackets, like this:

my_array = ['object_1','object_2','object_3']

Another way is to use the new method:

my_array = Array.new #no arguments, creates an empty array
my_array = Array.new(3) #one argument, creates an array with the specified number of values, which will be nil. In this example, it will create an array of 3 nil values: `[nil, nil, nil]`
my_array = Array.new(3, 'object') #two arguments, creates a array with the specified number of values with the specified value. In this example, it will create: `['object', 'object', 'object']`

1c. How do I access elements in an Array?

Arrays are ordered lists that use integers as an index. Each element in an Array is stored in a specific order and can be retrieved by calling the number it is associated with by using the #[] method. One thing to keep in mind, though, is that the ordered list starts at 0. The first element in an Array is at position 0, the second element is at position 1, etc.

Examples:

my_array = ['I','am',24]
my_array[0] #returns 'I'
my_array[1] #returns 'am'
my_array[2] #returns 24

You can also do the same thing using the at method.

Example:

my_array.at(1) #returns 'am'

1d. What are some other Array methods?

Hashes

2a. What are Hashes?

A hash is an unordered list of unique keys and their values. They are similar to Arrays. One key difference is that while an Array associates its list of values with an index of integers, a Hash allows you to assign any object type to the values as a key. So a Hash stores the key and the value in the list; kind of like a dictionary.

2b. How do I create a Hash?

One way to create hash is to put the keys and values you want to store in a set of curly brackets, like this:

my_hash = { 'gender' => 'male',
'legal' => true,
'height' => 62
}

Noticed how I used => to assign a key to a value and commas to separate each pair of key and value. Each key MUST be unique. There can NOT be a duplicate key in the same hash.

Another key difference is that hashes allows an alternative syntax, called symbols, as keys (marked by : in front of the name):

my_hash = { :gender => 'male',
:legal => true,
:height => 62,
}

Or (more conveniently):

my_hash = { gender: 'male',
legal: true,
height: 62
}

A second way to add a hash is:

my_hash = Hash.new
my_hash['gender'] = 'male'
my_hash['legal'] = true
my_hash['height'] = 62

2c. How do I access elements in a Hash?

Hash elements can be accessed in a similar fashion as Array elements, but instead of calling for the integer index, you would call for the key.

Examples:

my_hash['gender'] #returns 'male'
my_hash['legal'] #returns true

Default Hash Value:

Another key difference between Arrays and Hashes is that Hashes allow you to store a default value if the key is not assigned to any value, like this:

my_hash = Hash.new('default value')
my_hash['gender'] = 'male'
puts my_hash['gender'] #'male'
puts my_hash['legal'] #'default value'
puts my_hash['height'] #'default value'

2d. What are some other Hash methods?

Summary:

3a. Key Differences

Whew, that was quite a bit of information!

Here’s a little table that summarizes the key differences between Arrays and Hashes:

Arrays Hashes
Create new: my_array = []
my_array = Array.new
my_hash = {}
my_hash = Hash.new
Accessing elements: Via an index of integers, starting at 0 Via assigned unique keys, which can be any object
Other unique factors: Can use symbols as keys
Can set a default value for non-assigned keys

3b. Still not sure what the differences are or when to use what?

Here is a good summary I found:

  • An array is an ordered list of things: a, b, c, d
  • A hash is a collection of key/value pairs: john has a peugeot, bob has a renault, adam has a ford
  • Source: Stack Overflow

If you need to store a collection of things, use an Array. If you need to store a collection of things that are associated with something else, use a Hash.

Feel free to reach out to me if you still have any questions!

This blog has been initially published on tonymai.github.io.