Git Product home page Git Product logo

ruby-hash's Introduction

General Assembly Logo

Ruby Hashes

Instructions

Fork, clone, branch (training), bundle install

Objectives

By the end of this, developers should be able to:

  • Create a Ruby Hash using both the implicit ({}) and new constructors.
  • Assign a value to, modify, and delete a value in a Ruby Hash using a specified key.
  • Access a value in a Ruby Hash using a specified key.
  • Obtain an Array of keys from a Ruby Hash.
  • Explain why Symbols are preferred over Strings as keys in a Ruby Hash.

Introduction

In Ruby, "A Hash is a dictionary-like collection of unique keys and their values". In sharp contrast to JavaScript, Ruby Hashes are not the most general object in the language, but are instances of a specialized class for key/value storage.

Ruby Symbols

A Symbol is a sequence of characters that is stored at most once in any instance of the Ruby interpreter.

In Ruby, strings are compared a character at a time, but symbols are compared by object_id. This makes comparing symbols fast and therefore much more performant than strings when used as keys in a Hash.

Demo: Test Equivalency

Each of the following pairs of operations are equivalent:

> 'bob'.equal? 'bob'
=> false
> 'bob'.object_id == 'bob'.object_id
=> false
> 'bob'.eql? 'bob'
=> true
> 'bob' == 'bob'
=> true

But all of the following operations are equivalent:

> :bob.equal? :bob
=> true
> :bob.object_id == :bob.object_id
=> true
> :bob.eql? :bob
=> true
> :bob == :bob
=> true

We can create a symbol with arbitrary characters if we surround the characters with quotes (either :'<characters>' or '<characters>'.to_sym):

> :'&foo'.equal? '&foo'.to_sym
=> true

How does this compare to keys in JavaScript?

Creating Ruby Hashes

Let's look at different ways to create a Hash.

Demo: Hash Creation

> apartment = {}
=> {}
> apartment = Hash.new
=> {}
> apartment = Hash.new('')
=> {}
> apartment[:address]
=> ""
> apartment[:address] = { street: '255 Long Road', city: 'Awesomeville', bedrooms: 3}
=> {:street=>"255 Long Road", :city=>"Awesomeville", :bedrooms=>3}
> apartment.merge({rent: 1000})
=> {:street=>"255 Long Road", :city=>"Awesomeville", :bedrooms=>3, :rent=>1000}

Picking sensible defaults may not always be easy.

Code Along: Hash::new

Let's use the different forms of Hash::new to create some hashes in bin/code_along.rb.

Lab: Hash Shorthand

In bin/lab.rb create a hash using the shorthand syntax for assigning the keys :sq_ft :pets_allowed with a type-appropriate value of your choice. Then assign a default of [] to the hash and make sure that accessing non-existing keys return the default.

Assigning and Accessing Elements in a Ruby Hash

Demo: Accessing, Modifying, and Deleting

> apartment[:occupants] = []
=> []
> lee = {name: "Lee", age: 24, dog: "Fluffy"}
=> {:name=>"Lee", :age=>24, :dog=>"Fluffy"}
> adrian = {name: "Lee", age: 24, cat: "Scratchy"}
=> {:name=>"Adrian", :age=>25, :cat: "Scratchy"}
> apartment[:occupants].push(lee, adrian)
=> [{:name=>"Lee", :age=>24, :dog=>"Fluffy"}, {:name=>"Lee", :age=>24, :cat=>"Scratchy"}]
> apartment[:occupants][1].delete(:cat)
=> "Scratchy"
> apartment[:rent] += 150
=> 1150

Lab: Appending

Add roommate Bo to :occupants in the hash in bin/lab.rb. Append one or more properties of your choosing to the roommate objects, such as :job or :education.

Demo: Hash Keys

To get an Array of the keys that have been set in a hash, use Hash#keys.

> apartment.keys
=> [:address, :city, :bedrooms, :occupants, :rent]

Lab: Hash.new Initialized With Default

What if we wanted to instantiate our new hash with this default right off the bat? Checkout the Ruby docs on new hashes with default blocks.

Then, in bin/lab.rb initialize a new hash using Hash.new with a block that sets the default value (without using .default) of all keys to the string "Sorry, <keyname> does not exist".

  1. All content is licensed under a CC­BY­NC­SA 4.0 license.
  2. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact [email protected].

ruby-hash's People

Contributors

tdyer avatar rdegnen avatar tibbon avatar micfin avatar laurenfazah avatar jrhorn424 avatar payne-chris-r avatar bengitscode avatar

Watchers

Yenifer A. avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.