Man With Code 👨‍💻

In which I occasionally teach you things.

Programming With Ruby Episode 8, Hashes

Series: Ruby Programming

Covered In This Episode: 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: [sourcecode language="ruby"] my_hash = {} [/sourcecode] Items are defined like this: [sourcecode language="ruby"] birthdays = {"Amy" => "May", "Dakota" => "January"} [/sourcecode] 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: [sourcecode language="ruby"] brithdays["Amy"] #=> May [/sourcecode] You can define new keys and values: [sourcecode language="ruby"] birthdays["Zack"] = "April" [/sourcecode] Iterating Over Hashes Hashes have an each method like arrays do: [sourcecode language="ruby"] 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 [/sourcecode] 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 [email protected] Thanks for watching, goodbye!