Programming With Ruby Episode 8, Hashes

Programming With Ruby Episode 7, ArraysProgramming With Ruby Episode 9, Flow Control

Covered In This Episode:

  • What are Hashes?
  • Hash Creation
  • Hash Accessing
  • Hash iteration
  • Hash Methods

Transcript:

Hello Everybody and welcome to Programming With Ruby Episode 8,
Hashes. I’m Tyler,and this video is brought to you by, manwithcode.com

In this episode I will be telling you what hashes are, how you can
create them, access them, and iterate over them. Finally at the end I
will show you some useful methods that hashes have.

What Are Hashes?

Hashes are like arrays, which you learned about in the previous
episode. Except that they have no order, and instead of being accessed
by an index number, they are accessed by what is called a key (which
can be anything). That key points to a value, which is the actual data
inside the hash

Arrays are used for lists of data, where hashes are used to relate
data. I may have a hash where the keys are my friend’s names, and the
values are their birthdays.

Hash Creation

Similarly to how arrays are created with square brackets, hashes are
created with curly brackets:

my_hash = {}

Items are defined like this:

birthdays = {"Amy" => "May", "Dakota" => "January"}

Each key-value pair are separated by a comma, and their relation is
defined with =>

Accessing Hashes

You can access hashes in almost the same way you access arrays, except
by using the key value, instead of an index number:

brithdays["Amy"] #=> May

You can define new keys and values:

birthdays["Zack"] = "April"

Iterating Over Hashes

Hashes have an each method like arrays do:

my_hash = {"cat" => "hat", "dog" => "log"}
my_hash.each do |pair|
	puts "Key: " + pair[0]
	puts "Value: " + pair[1]
end
#=> Key: cat
#=> Value: hat
#=> Key: dog
#=> Value: log

They also have each_key and each_value which let you iterate over each
key or value in a similar way.

Useful Hash Methods

delete(key) deletes a key-value pair
empty? True or False if the hash is empty
keys returns the keys
values returns the values
size how many key-value pairs there are

That wraps it up for this episode!

Please donate, or I will stop making these videos. There should be a
link to donate to the right of this video.

If you have any questions or comments leave a comment on this page or
email me at tyler@manwithcode.com

Thanks for watching, goodbye!

Programming With Ruby Episode 7, ArraysProgramming With Ruby Episode 9, Flow Control

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.