Category Archives for Programming

Ruby Hash Methods

Ruby Hash – Definition, Examples & Methods: The Ultimate Guide

What is a Ruby hash?

A hash is a data structure used to store data in the form of UNIQUE key-value pairs. Unlike arrays, there are no numerical indexes, you access the hash values with keys.

Examples include:

  • A list of country names & their corresponding country codes (like ES ⇾ Spain)
  • A dictionary, where every word has a list of possible definitions
  • A domain name & it’s IP address

Using a hash in your Ruby programs can speed up your code when used in the right situation.

In other words:

You have data that is (or can be transformed into) a dictionary-like format, where data can be grouped by keys & associated values.

How to Create a Hash


We get the general idea of what a hash is, but how do you create one?

Like this:


That’s an empty hash!

A hash with three key/value pairs looks like this:

{ a: 1, b: 2, c: 3 }

Where a is a key, and 1 is the corresponding value for that key. Notice that the key-value pairs are separated by commas.


Let’s look at how you can use hashes in your Ruby projects with common hash methods.

Storing Values in a Ruby Hash

You can create a hash with a set of initial values, as we have already seen.

Here’s another example:

fruits = { coconut: 1, apple: 2, banana: 3 }

Another option is to add new values into an existing hash.

Like this:

fruits[:orange] = 4

This is :orange as the hash key, and 4 as its corresponding value.

Why is the colon before the word :orange when we access a value & after the word orange: when we create a hash? It’s a nicer syntax that allows you to create hashes without the hash-rocket (=>) symbol, which is a valid, but older way to do it.

Values can be any Ruby object.


  • Strings
  • Integers & Floats
  • Arrays

Keys can also be anything, but symbols (like :banana) & strings are the most common type of keys you’ll find.

Remember that…

Keys are unique, we can only have one :orange key, or one :apple key.

When you add the same key twice you change its value.

How to Access Values From a Hash

You access a hash by key.

If you need to access the values directly, then a hash may not be the right structure for your data.


# 4

This is the whole point of hashes, to quickly look up an item by its key.

If a key doesn’t exist, you’ll get nil.

# nil

As an alternative, you can use the fetch method, which allows you to provide a default value.


fruits.fetch(:peach, 0)

If you use fetch without a default value (the 2nd argument), Ruby will raise a KeyError exception.

That’s helpful because you’ll know what key is missing.

How to Merge Two Ruby Hashes

You can take two hashes & merge them together into a new hash.

What method does this?

Well, it’s not hard to guess this one. The method’s name is merge.

Here’s how to use it:

defaults    = { a: 1, b: 2, c: 3 }
preferences = { c: 4 }

# {:a=>1, :b=>2, :c=>4}

Notice that because keys are unique, newer values overwrite older values.

You could use this fact for interesting solutions, like creating a “defaults” hash that users can override by passing their own hash.

If you need more control over how keys are merged you can pass a block.

Like this:

defaults.merge!(preferences) { |key, old, new| [old, new].max }

Where old are the values coming from defaults, and new are the values coming from preferences.

Multiple Values For One Key

In a dictionary…

Words are unique, but they can have multiple values (definitions) associated with them.

You can do this in Ruby!


dictionary = {
  opportunity: [
    "a set of circumstances that makes it possible to do something",
    "a situation or condition favorable for attainment of a goal"
  creativity: [
    "the use of imagination or original ideas to create something new",
    "the ability to create",
    "the process where new ideas emerge from combining existing ideas in new ways"


Where dictionary[:creativity] gives you an array & [1] gives you the 2nd element from that array.

In other words:

The key is a symbol & the values are arrays. When you access the hash you get an array back which you access normally, like any other array.

How to Sort a Hash

You can sort arrays. But did you know that you can also sort hashes?

When you sort a hash, it’s sorted by key.


{ b: 1, a: 2 }.sort

# [[:a, 2], [:b, 1]]

But you can also sort them by value:

{ c: 3, b: 1, a: 2 }.sort_by(&:last)

You’ll notice that what you get from sorting a hash is not another hash…

It’s an array!

But you can convert this array back into a hash, using the to_h method.

Get All Keys & Values From a Hash

If you want a list of all the hash keys, good news, there is a method for that!

Here it is:

{ apple: 1, banana: 2 }.keys

# [:apple, :banana]

There’s also a method which gives you an array containing the values:

{ apple: 1, banana: 2 }.values

# [1, 2]

If you want to know if a key exists in a hash, instead of getting an array of them, use the key? method.

This method returns a true or false value.


You’ve learned about Ruby hashes, a helpful data structure which is composed of key-value pairs. You also learned how to access a hash by key, and how to store new data in a hash.

Now open up irb (or pry) & start playing with hashes!

Thanks for reading 🙂

Ruby Self Keyword

What Is Self in Ruby & How to Use It (Explained Clearly)

If you’re learning Ruby you may find the use of the “self” keyword very confusing.

How does it work?

What is self, exactly?

It’s a Ruby keyword that gives you access to the current object.

If you don’t know what objects are, watch this video I made for you. It’s related to Object-Oriented Programming.

This “current object” depends on the context.


Yes, the context is where your code is at any given moment.

Here’s an example:

If your code is inside an instance method, self is an instance of that class. In other words, self is an object.

You can see this in action yourself.

Run this code:

def coffee
  puts self

# main

This code defines & calls a coffee method which prints the value of self.

Why does it print main?

Because it’s the name of the top-level object, it’s an object where you’ll find all the methods defined outside a class.

Like our coffee method here.

But if you define a method inside a class named Cat, then self would be a Cat object.

As seen here:

class Cat
  def meow
    puts self
# <Cat:0x7a14c5>

From these examples, we can tell that the value of self changes depending on where you use it.


I believe you can understand anything better by understanding its purpose.

Why is self useful?

Let’s look at some examples.

Using Self For Disambiguation

One practical use for self is to be able to tell the difference between a method & a local variable.

It’s not a great idea to name a variable & a method the same. But if you have to work with that situation, then you’ll be able to call the method with self.method_name.

Here’s what I mean:

class Example
  def do_something
    banana = "variable"

    puts banana
    puts self.banana

  def banana

# "variable"  => puts banana
# "method"    => puts self.banana

Here we have a banana local variable, inside the do_something method, but we also have a banana method.

A local variable takes priority.

That’s why we need to use self here if we want to call the banana method, instead of printing the value of the banana variable.


Let’s look at a more common use case… Defining class methods!

Using Self To Define Class-Level Methods

Number ONE use for self, without a doubt, is to define class-level methods.

I’m sure you’ve seen them.

These def self.method_name method definitions.

Like this one:

class Salad
  def self.buy_olive_oil
    # ...


This self here is equivalent to Salad, the class name.

Why is this useful?

Because we don’t have to use the class name for each method definition, making our code easier to change if we change the class.

It also makes the code less noisy & better to read.

That’s why we do def self.buy_olive_oil instead of def Salad.buy_olive_oil.

Other Uses For Self


There are even more uses for self, so it’s a helpful thing to be familiar with.

For example:

You can use it in a method to compare the current object with another object.

Something like this:

def ==(other)
  self == other

You can also use self for debugging purposes, to find out which object you’re working with.

Like this:

p self

Or you can use it as a return value, to implement design patterns like the Builder Design Pattern.


class Salad
  def initialize
    @ingredients = []

  def add_nuts
    @ingredients << :nuts


my_salad =

In summary, here's a list of helpful uses for self:

  • Define class-level methods
  • Use an instance method when you have a local variable of the same name
  • Returning Self (builder pattern)
  • Debugging
  • Comparing objects (==)
  • Default receiver of method calls

Self vs Itself

One more thing we should look at before we are done with this topic.

The Kernel#itself method.

It's a method that you can call on an object & the object will return itself.



# [1, 2 ,3]

This example filters nil & false values.

Understanding the difference:

  • self is a keyword. It's value depends on where you use it
  • itself is a method. It's value depends on what object you use it on (in 1.itself, 1 is the object)

Hope that's helpful.


You have learned about Ruby self keyword, exactly what it is, why it's useful & how to use it.

Now it's your turn to give it a try.

Thanks for reading! 🙂

Rails Scaffolding Guide Featured Image

What is Scaffolding in Ruby on Rails?

You may be learning Rails & you read that you have to create a “scaffold” to get your Rails application started…


You can do this using the rails g scaffold command.

But what is scaffolding?

“Scaffolding is a temporary structure used to support a work crew to aid in the construction, maintenance and repair of buildings, bridges and all other man-made structures.” – Wikipedia

Translated into Rails:

A scaffold is a set of automatically generated files which forms the basic structure of a Rails project.

These files include:

  • A controller
  • A model
  • Views for every standard controller action (index, edit, show, new)

A new route.

And a migration to prepare your database.

Let’s see an example!

How to Use The Rails Scaffold Command

An example of scaffolding a project for a website about books would look like this.

rails g scaffold books

You should see a lot of text scrolling by, which details the files being created.

This example creates:

  • A BooksController
  • A Book model
  • A new resources :books route added to your config/routes.rb file
  • A set of testing-related files
  • View files under app/views/books (five in total)


That’s a lot of stuff.

If you want to undo this scaffolding, right after creating it, you can use the following command.

rails d scaffold books

Where “d” means “destroy”.

Keep in mind that this will DELETE the files created by the scaffolding process.


Before you can use your scaffolded code you have to run your migrations to update your database schema.

Use the rails db:migrate command.

If no error messages show up, you’re ready! You have a basic structure for your new Rails application, or for a new feature that needs a new model, views & corresponding controller.


Run rails server.

Open your browser to localhost:3000/books & you should be able to see the results!

Rails Scaffolding With Extra Fields

By default…

Your model only gets timestamp fields, which means that the only information that you can record about your books (or whatever model you’re working with) is the time at which they were created, or updated.

Here’s how to scaffold with extra fields:

rails g scaffold books title:string author:string publication_year:integer

If you generate your scaffolding like this, you’ll have 3 fields to work with.

A title, an author, and a publication year.

That’s a bit more interesting than just having the database timestamps.


This the same syntax we use for creating migrations with rails g migration.

Generating Specific Components

Scaffolding creates things you may not need or want right now.

But Rails is nice.

You can create individual components, like controllers, using the rails g (g for generate) command.


  • rails g controller Fruit
  • rails g model Fruit name:string color:string (creates model + migration)
  • rails g migration CreateBook title:string year:integer (creates migration only)

One of the big benefits of using a scaffolding command is that all the files are created using the correct naming conventions, which avoids strange error messages. It also saves you the work of having to manually create these files.


It’s considered good practice to delete auto-generated files that you don’t plan on using. So after using a generator like “g controller”, review the list of files created & remove those that you don’t need.


You’ve learned about scaffolding in Ruby so you can quickly jumpstart a new Rails application to practice with.

As you learn more you may want to let go of scaffolding.

But you can still generate individual controllers, models, or view files when you need them.

Thanks for reading! 🙂

Ruby directory operations featured image

How to Work With Directories in Ruby

Did you know that you can navigate your file system with Ruby?

With the Ruby “Dir” class.

You can list directory entries, change your current directory & even create new folders!

Here’s an example:

filenames = Dir.entries(".")

This entries method returns an array of filename entries. Every entry is a string, so you’ll need to combine this with the Ruby File class if you want to actually read these files.

Btw, this dot (.) represents the current directory.

This will be the directory your code is running from, NOT the directory you’re (in your terminal) when running the code.

Because of that…

It can be helpful to check your current directory by using the Dir.pwd method.


Let’s learn how to use the Dir class to create new directories (mkdir), rename them (mv), and find file names that follow a specific pattern (glob).

Using Ruby’s Mkdir Method To Create A New Directory

If you want to create a new folder with Ruby you can use the Dir.mkdir method.



If given a relative path, this directory is created under the current path (Dir.pwd).

You can get a few errors:

  • Directory already exists (Errno::EEXIST)
  • Permission denied (Errno::EACCES)
  • You’re trying to create a folder under another folder that doesn’t exist yet (Errno::ENOENT)

The last error usually happens when you’re trying to create nested directories.

Or if you’re using an absolute path that doesn’t exist.

Two solutions:

  • Check if the directory exists before creating it (with Dir.exists?)
  • Use a more advanced class (next section)

Let’s keep learning!

Advanced Operations With The FileUtils Module

If you need an extra bit of horsepower you can bring in the FileUtils module from the standard library.

It includes methods like mkdir_p that create nested directories in one step.

Here’s an example:

require 'fileutils'


Pretty cool, right?

That’s not all, FileUtils also brings extra options for all file operations in the form of keyword arguments. Like the verbose option (prints Linux commands) & the noop (don’t change files) option.

Give it a try!

How to Rename Directories

Ruby allows you to do every operation you can do from your Operating System user interface, or from a terminal.

For example…

You can rename a directory like this:"/tmp/a", "/tmp/b")

You’ll also need to use FileUtils here because mv is not available on the Dir class.

How to Change Your Current Directory

Because all directory operations are run from the current directory, you may want to change it.

You can use the Dir.chdir method to do this.


Dir.chdir("/tmp") { Dir.entries(".") }

This works in two ways:

  • With a block, the current directory changes only for the code inside the block
  • Without a block, it changes for all the code after the method call

Notice that chdir only works within your Ruby process, it doesn’t affect the “outside world”.

In other words…

It won’t change your shell’s working directory after your Ruby program stops running.

Listing Files & Directories With Pattern Matching

Want to find all Ruby files in a folder? An easy task with the glob method!



You can use any other extension you want, like “.txt”, or “.yml”. Or any other text that’s part of the file name.

Want to find files inside all folders?

Yep, it’s possible:


The result is an array with all the file names, including the relative path. You can remove the path & get only the file name by using the File.basename method on every file of the list that you get from glob.


You have learned how to work with directories in Ruby using the Dir & FileUtils classes.

Now it’s your turn to put this into practice.

Thanks for reading! 🙂

Java vs Ruby (Featured Image)

7 Major Differences Between Java & Ruby

How do you move from Java to Ruby?

In this guide, you’ll learn what are the major differences between the two languages to help you make the jump.

It’s great for the many people looking to move from Java/C# to Ruby.


If you’re just curious about the differences, then this is also for you.

Let’s do this!

Static Typing vs Dynamic Typing

Typing style is the biggest & most notable difference when looking at code for either programming language.

Here’s the situation:

  • Java uses static typing
  • Ruby uses dynamic typing

What does that mean, exactly?

Typing refers to how variables & method arguments work.

A strongly (or statically) typed language has to declare what types (classes) every variable can accept.

It looks like this:

int n = 1;

Where int is the type, in this case, Integer.

Why is that useful?

Because if you try to assign any other type of object to this variable, the compiler will raise an error & your program won’t even get to run.

This means that you’ll always know what kind of object you’re working with.

With the disadvantage of being less flexible.

In contrast…

Dynamic typing is all about flexibility, variables aren’t tied to a particular type, so the type can change.

Here’s an example:

n = 1
n = "abc"

The downside is that you may run into more errors if your code is sloppy & you don’t get as much when reading code.

That’s one of the major differences!

More in the next section.

Syntax: Simple Things & Boilerplate

Java is the king of boilerplate.

Boilerplate is all that “setup” code that you have to add just to make your code syntactically valid.

As a result…

Java makes SIMPLE things complicated!

Hello World in Java:

class Hello {
  static public void main() {
    System.out.println("Hello World");

Then you have to compile this into a class file & run it.

Two steps!

(IDEs help with this.)

Another difference is that expressions in Java end with a semicolon, which is not required in Ruby. You can also leave out parenthesis in Ruby, most of the time.

Hello World in Ruby:

puts "Hello World"


That’s it.

It seems like Ruby results in cleaner code. Agree?

On top of that…

You can run this code with a single command from a terminal!

No compilation step needed.

Playing With Code: Built-In REPL

Ruby comes with irb, which makes testing out a bit of code really quick.

You don’t even need to save a file.

Or open an editor!

Java doesn’t have this built-in, at least it doesn’t until Java 9.

File Names & File Organization

Java forces a specific file naming structure & organization.

For example:

If you have a (public) class named Hello, the file name MUST be

This isn’t the case in Ruby.

Also, we don’t have the concept of a private class in Ruby.

Exception Handling

Java has two types of exceptions:

  • Checked exception
  • Unchecked exception

The difference?

You HAVE to handle checked exceptions!

Or your program won’t even run.


Ruby has only one type of exception.

You can handle it if you want, the interpreter won’t complain about it, but it may end up crashing your program.

Compiler & Language Licensing

Lastly, let’s talk about licensing.

This isn’t usually a problem with programming languages.


Because they’re open source, with one person as the head maintainer & designer.

Java is different here.

It to a big corporation (Oracle) & that has implications on it’s licensing.

In fact:

There are two versions of the Java runtime, “Oracle JDK”, which (if I understand correctly) starting with version 9 is a commercial product.

Then you have “Open JDK”, which also belongs to Oracle.

But it has an open-source license.

Library & Code Distribution

Another MAJOR difference, one of my favorites (also Matz’s favorite) about Ruby is RubyGems.

It makes distributing libraries (like HTTP clients) much easier.


  • There is a central repository
  • It’s integrated into the language
  • Many open-source gems are available & easy to find

As far as I know, Java doesn’t have anything close to this, so this is a major win for Ruby.


You’ve learned about the major difference between Java & Ruby. Including things like static typing, boilerplate, and file naming.

Now you’re better prepared to understand Ruby so you can make the correct decision for you.

Thanks for reading! 🙂

1 2 3 34