SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
-
Mar 9, 2009, 08:30 #1
- Join Date
- Oct 2008
- Posts
- 19
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Can somebody please give me the answer to this
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 = ?
-
Mar 9, 2009, 12:09 #2
- Join Date
- Feb 2007
- Posts
- 270
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
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]
Oh, and if you want to escape the smiley injection, use code tags:
Code::one instead of : one
-
Mar 9, 2009, 14:33 #3
- Join Date
- Oct 2008
- Posts
- 19
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thank you.
This wasn't my homework though, it is something I had to do earlier and I did it wrongI wasn't sure what the right answer was so that's why I asked the question. Not that I was cheating don't worry I didn't have that much time
Thank for the code tags too I'll keep that in mind.
Bookmarks