Ruby is dynamic, flexible and robust programming language. It is also very easy language to start with. If you are new to programming Ruby will help you start the easy way. Take the next step on your journey to learn Ruby. Learn about topics such as hashes, symbols and control flow.

Getting Started With Ruby the Easy Way Part 1 (Comments, Variables, Strings).

Getting Started With Ruby the Easy Way Part 2 (Data Types Pt1).

Getting Started With Ruby the Easy Way Part 4 (Control Flow Pt2).

Getting Started With Ruby the Easy Way Part 5 (Control Flow Pt3).

Getting Started With Ruby the Easy Way Part 6 (Methods).

Getting Started With Ruby the Easy Way Part 7 (Recursion, Scope, OOP Pt1).

Getting Started With Ruby the Easy Way Part 8 (OOP Pt2).

Getting Started With Ruby the Easy Way Part 9 (OOP Pt3).

Getting Started With Ruby the Easy Way Part 10 (OOP Pt4 and Beyond).

Data Types Pt2

In the the first part, you’ve learned about the first two primary data types available in Ruby, strings and constants. Then, in the second part, you’ve learned about the another four, integers, floats, booleans and arrays. There are eight of them in total. This means that there are two more you need to learn about. Namely, hashes and symbols.

Hashes

Hashes are another very useful data type. Ruby developers like to use them in cases when arrays are not sufficient to get the job done. This is due to the fact that hashes, to some degree, look similar to arrays. They too allow you to store other objects, in any data type. Just like arrays. In arrays, you store data using indexes. This is where hashes are different.

When you want to store some data in a hash, you do it in the form of a key/value pair. When you want to retrieve, or access, specific data (the value) you don’t use index. Instead, you use specific key you previously assigned to that value. One way to think about hashes is to imagine areal dictionary. Here, the original word is a key. The translation of that word is a value.

For example, let’s say you have a dictionary that translates from English to Spanish. You want to translate the word “computer”. In that case, the word “computer” is the key while the Spanish version, “computadora”, is the value. You would use the “computer” key to retrieve the “computadora” value from the hypothetical hash called “dictionary”.

When you want to create a new hash, and populate it with data, the syntax is simple. You assign a key to a value using =>. Some Ruby developers like to call this a “hashrocket”. When you want the hash to contain more than one pair, you separate these pairs with commas (,). Then, you wrap all these pairs with curly braces ({}). This is the next difference between hashes and arrays. Arrays use square brackets ([]) and hashes curly braces ({}).

This is not actually the only way to create a hash. You can also create it using Hash object and new method. This will create new empty hash. Then, when you want to add a new key/value pair you use the name of the hash, followed by square brackets with the key inside, followed by assignment operator (=), followed by the value you want to assign to that key.

This is almost the same thing you do in case you work with an array. At this moment, you are the only difference is that you are replacing the array index inside the brackets with a key. Remember that you can use any kind of data type, or object, as a key. And, you can store any kind of data type or object as a value. When you want to retrieve the value?

Then, you use the same syntax, but omit the assignment part. Meaning, you use the name of the hash, followed by square brackets with specific key. Another way to retrieve a value is using fetch method with the key as an argument, inside the parentheses. If you try to retrieve a value from pair that doesn’t exist, Ruby will return nil. What if you want to change existing value?

You use the same syntax as you would if you would want to create a new key/value pair. Now, you will just override the existing value in existing pair, instead of adding a new pair. That was creating, retrieving and changing. What if you want to delete some pair? There are two options you can choose from. First, you can delete a pair by just changing the value to nil, using specific key. Second option is calling the delete method, with the key as an argument inside the parentheses.

Just like with arrays, there are a lot of things your can do with hashes. For example, you can merge hashes together using merge method. You can also retrieve all values using keys method. This will return the values inside the hash in the form of an array. You can also use length or size when you want to find out how many key/value pairs specific hash contains. You can find all available methods in Ruby docs for hashes.

Side note: Starting with Ruby 1.9, there is another, “modern”, syntax you can use to create a hash. You can replace the “hashrocket” (_=>_) with colons (_:_). However, there is a catch. Using colons will tell Ruby that you want the _keys_ to be _symbols_. This also means that you can’t use this “modern” syntax if you want to use _symbols_ for _keys_.

There is one more, important, thing to remember. When you use modern syntax you have to use _symbols_ to retrieve data from hash. This is logical. Ruby created all _keys_ as _symbols_. Therefore, when you want to retrieve any _value_ assign to specific _key_ you also have to use a _symbol_.

##
## Create an empty hash
emptyHashExample = Hash.new

## or
emptyHashExample = {}

puts emptyHashExample ## Outputs: {}

##
## Add new key/value pairs an empty hash
emptyHashExample["one"] = "uno"
emptyHashExample["two"] = "dos"
emptyHashExample["three"] = "tres"

## Print the content of emptyHashExample to console
puts emptyHashExample ## Outputs: {"one"=>"uno", "two"=>"dos", "three"=>"tres"}

puts emptyHashExample["one"] ## Outputs: uno

##
## Create hash with content
germanHashExample = {
  "one"=>"ein",
  "two"=>"zwei",
  "three"=>"drei"
}

## Print the content of germanHashExample to console
puts germanHashExample ## Outputs: {"one"=>"ein", "two"=>"zwei", "three"=>"drei"}
puts germanHashExample["three"] ## Outputs: drei

## or with "modern" syntax, using ":"
germanHashExample = {
  one: "ein",
  two: "zwei",
  three: "drei"
}

## Print the content of germanHashExample to console
## Notice that when you use the modern syntax you also
## have to use `symbols` when you want to retrieve the data
## germanHashExample[:two] instead of germanHashExample["two"]
## using germanHashExample["two"] will return nothing.
puts germanHashExample ## Outputs: {:one=>"ein", :two=>"zwei", :three=>"drei"}
puts germanHashExample[:two] ## Outputs: zwei

##
## Change the content of existing hash
hashExample = {
  "one"=>"Change this."
}

puts hashExample ## Outputs: {"one"=>"Change this"}

## change the value of "one"
hashExample["one"] = "This is a new value"

puts hashExample ## Outputs: {"one"=>"This is a new value"}

##
## Delete content from hash
hashExample = {
  "name"=>"Anthony",
  "age"=>35
}

puts hashExample ## Outputs: {"name"=>"Anthony", "age"=>35}

## delete the "age" pair
hashExample.delete("age")

puts hashExample ## Outputs: {"name"=>"Anthony"}

## or if you use the modern syntax
hashExample = {
  name: "Anthony",
  age: 35
}

puts hashExample ## Outputs: {:name=>"Anthony", :age=>35}

hashExample.delete(:age) ## you must use symbol (notice the ":")
puts hashExample ## Outputs: {:name=>"Anthony"}

##
## Merge two hashes
hashOne = {
  "foo"=>"bar"
}

hashTwo = {
  "bar"=>"bazz"
}

## merge hashOne and hashTwo into a new hash, hashThree
hashThree = hashOne.merge(hashTwo)

puts hashThree ## Outputs: {"foo"=>"bar", "bar"=>"bazz"}

##
## Print all keys stored in the hash
hashFoo = {
  "foo"=>"bar",
  "bar"=>"bazz"
}

puts hashFoo.keys

## Outputs:
## foo
## bar

hashFoo = {
  "foo"=>"bar",
  "bar"=>"bazz"
}

##
## Print all values stored in the hash
puts hashFoo.values

## Outputs:
## bar
## bazz

##
## Get the length or size of a hash
hashFoo = {
  "foo"=>"bar",
  "bar"=>"bazz"
}

puts hashFoo.size ## Outputs: 2
puts hashFoo.length ## Outputs: 2

#ruby #programming #design development

Getting Started With Ruby the Easy Way Pt3
1.50 GEEK