Book Image

Comprehensive Ruby Programming

By : Jordan Hudgens
Book Image

Comprehensive Ruby Programming

By: Jordan Hudgens

Overview of this book

Ruby is a powerful, general-purpose programming language that can be applied to any task. Whether you are an experienced developer who wants to learn a new language or you are new to programming, this book is your comprehensive Ruby coding guide. Starting with the foundational principles, such as syntax, and scaling up to advanced topics such as big data analysis, this book will give you all of the tools you need to be a professional Ruby developer. A few of the key topics are: object-oriented programming, built-in Ruby methods, core programming skills, and an introduction to the Ruby on Rails and Sinatra web frameworks. You will also build 10 practical Ruby programs. Created by an experienced Ruby developer, this book has been written to ensure it focuses on the skills you will need to be a professional Ruby developer. After you have read this book, you will be ready to start building real-world Ruby projects.
Table of Contents (20 chapters)

Iterating over a hash for a key or value

You already learned how to iterate through a hash in one of our previous sections, however, it's a very critical task that you'll be using quite often. With that in mind, I'm going to discuss how it works in more detail. Also, I'm going to show you how you can iterate over only the keys or values.

I'm going to start with the hash we created in the previous section:

people = { jordan: 32, tiffany: 27, kristine: 10, heather: 29 } 

When you want to only grab the keys, your code can be like this:

people.each_key do |key| 
puts key
end

If I run this code, it prints out each one of the keys like this:

Now, to iterate through the values, we can leverage the each_value iterator method, like this:

people.each_value do |value| 
puts value
end

This will print out the values, which in this case, are the ages of people...