How to Use the Map Method in Ruby - Part 2
In this lesson, we are going to go much deeper into the map method and explore practical ways of using the method.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson, we are going to go much deeper into the map method and explore practical ways of using it in real world application.

I'm going to start by reviewing the last example we did in the previous lesson. In this script we created a Hash from an array of numbers. However in our example we're going to build in some custom behavior. We are going to convert a sentence into an array of words and create a hash that takes each word as the key and the length of each word as its corresponding value. The code for this will be:

Hash[ %w(A dynamic open source programming language).map { |x| [x, x.length] } ]

If we execute this code, the first Hash element should be the word and its corresponding value should be the length of the word. Let's see the output.

{"A"=>1, "dynamic"=>7, "open"=>4, "source"=>6, "programming"=>11, "language"=>8}

This worked perfectly. The first key is A and its value which is the length is 1. The second key is dynamic and its value is 7, the third value is open and its value is 4, and so on.

Next, we are going to see how you can use the map method in a real-world application, so you know where and how to use it.

If you go to google.com and try to search for a keyword such as ruby programming language, the URL would be something like this:

https://google.com/?qws_rd=ssl#safe=off&q=ruby+programming+language

Now, what happens if you go to the URL and remove the & and + values?

If you tried to pass these values into an API as an HTTP request, (something you'll do regularly when building Rails applications), this would throw an error.

In a real-world application imagine that you get a value that comes in as individual words. You would want to combine them together with the & character to get a URL safe string. We are going to do exactly this using our map method.

For example, let's say we have a set of hash values, namely foo and bar that have the keys as a and b respectively. To combine them into a safe URL, we can use this code:

{:a => "foo", :b => "bar"}.map {|a,b| "#{a}=#{b}" }.join('&')

In this code, I'm creating a hash with the symbol using the curly bracket syntax and I am using two variables to iterate through the collection. The first variable a is the key while the second variable b is the value. After stringing them together with the = sign I'm using the symbol & as a string here that joins the next set of values in the hash.

If you hit return, your output should be:

a=foo&b=bar

So now you know a number of practical ways to utilize the map method in Ruby programs.