
Originally Posted by
milandobrota
Given the following two lines, create a Hash object that
maps the keys to the corresponding values and assign it to the "hash"
variable. Do all of this in one line, less than 80 characters,
without using hard-to-read variable names (ie, no single character
variable names allowed). Assume that the keys and values arrays are
already sorted so that keys[0] should be the first key and values[0]
should be the corresponding value, and so on.
keys = [ : one, :two, :three, :four]
values = [1, 2, 3, 4]
hash = ?
OK, I'll give you this answer to get you started, but isn't it cheating to ask netizens to do your homework for you?
Generally, if the answer to a ruby programming question isn't obvious, you're looking in the wrong place. In this particular instance, if you haven't found the solution yet, you're looking in Hash, and not Array.
Looking first in Hash, we see we can convert a straight array to a hash by simply using Hash[ key1, val1, key2, val2 ... ] so the problem now is how to convert the two arrays into one interleaved array. And for that we need to turn to the Array object.
We can see the zip function starts the interleaving process by creating a multidimensional array out of two+ arrays. And the way to bring that back down to a one-dimensional array is to flatten it.
Given that, we get:
Code:
hash = Hash[*keys.zip(values).flatten]
Since I believe all students need to do some work on their own, I'll leave it as exercises for the reader to explain why the asterisk is necessary and to handle the problem of one array being longer than the other.
Oh, and if you want to escape the smiley injection, use code tags:
Code:
:one instead of : one
Bookmarks