Ruby Hashes

Ruby hashes. Key Value pairs. This was most definitely my most challenging beginner concept to understand. I still struggle with it. I get the basics, now, but doing more complex operations still confuse me!

What does a hash look like? Well for a great, I mean terrific example. I’ll turn my dog named Penny into a hash. She’s 6 years old, a black lab and she is potty trained.

# This is how you're supposed to create hashes in Ruby. When I say "supposed to" I'm talking about the keys, they're supposed to be symbols. More on that later
penny = {
  name: "Penny",
  age: 6,
  potty_trained: true
}

Let’s say you want to access the age of Penny.


    penny[:age]
    => 6

    penny[:name]
    => "Penny"

    penny[:potty_trained]
    => true

You go pen pen!

But there are also weird ways in which you will see hashes defined. I’ve identified some weird ones below.


    penny = {
      "name" => "Penny",
      "age": 6,
      "potty trained": true
      }

    penny["name"]
    => "Penny"

    penny[:name]
    => nil

See the hash rocket? =>, that means your key is a string and therefore need to use key that is a string to get value.

Let’s move on to age. Which is defined as “age”:


    penny["age"]
    => nil
    penny[:age]
    => 6

When the : notation is used, it will automatically turn your string into a symbol. UNLESS there is a space…. like we have in potty trained


    penny["potty trained"]
    => nil

    penny[:"potty trained"]
    => true

Soo weird. It’s a symbol, but it has a string. It’s got the quotes.


    :"potty trained".is_a? Symbol
    => true

    :"potty trained".is_a? String
    => false

So I’ve probably confused you more than even helped you here. Just know it’s all fucked up, and you can create hashes all sorts of ways, but if you see the => in the hash, you know you need to use a key that is a String. However, if you see the :, you need to use a key that is a Symbol.

Hashes in Arrays

A lot of times when working with APIs, your hash will come within an array. Sure it’s a great way to structure data, but as a noob it makes you want to punch the creator in the dick.

Let’s say we have multiple pets. Imagine it’s an API. You call out to the API and it gives you a response like…


    my_pets = {
      "pets" => [
        {
          "name" => "Penny",
          "age" => 6
        }, {
          "name" => "Biscuit",
          "age" => 3
        }
      ]}

    my_pets["pets"].is_a? Array
    => true

    my_pets["pets"][0]["name"]
    => "Penny"

    my_pets["pets"][1]["name]
    => "Biscuit"

So if we want to loop through the array and print each pet name?


    my_pets["pets"].each do |pet|
      puts pet["name"]
    end

And you should see Penny and Biscuit printed to the console.

Weirdness in the API Response, turn it to TRUE JSON


    my_pets = {
      \"\pets\"\ => [
        {
          \"\name\"\ => \"\Penny\"\,
          \"\age\"\ => 6
        }, {
          \"\name\"\ => \"\Biscuit\"\,
          \"\age\"\ => 3
        }
      ]}

Sometimes you get a response from an API and it looks like that. With all the \, really annoying. But the solution is simple.


    parsed_pets = JSON.parse(my_pets)

That will get your response into a workable format where everything works.

Complex maneuvers with Arrays and Hashes

Sorting an array by hash value.


    my_pets = {
      "pets" => [
        {
          "name" => "Penny",
          "age" => 6
        }, {
          "name" => "Biscuit",
          "age" => 3
        }
      ]}


    my_pets["pets"].sort_by do |pet|
      pet["age"]
    end
    =>  [{"name"=>"Biscuit", "age"=>3}, {"name"=>"Penny", "age"=>6}]

.sort_by is an Array function which looks at the value returned in the block, then sorts the entire array based upon values returned in the block. So by calling, pet["age"] from within the block, we are going to sort the array by a value in the hash. Pretty fucking nifty!

http://stackoverflow.com/questions/3154111/how-do-i-sort-an-array-of-hashes-by-a-value-in-the-hash for more information, but as always. I prefer my excellent and remarkable and absolutely mind-blowing examples. Rather than just banging stuff against the wall, I’m beginning to understand it. Slowing down to speed up.

Grab Array Elements with unique value in Hash

http://stackoverflow.com/questions/4841187/unique-on-an-array-of-hashes-based-on-value Really freakin cool.

Post Content