0

Last newbie question for today. There is a hash:

h = {a: 1, b: 2, c: 3}

How to implement convert_to_arr(h) method with such output:

convert_to_arr(h) 
# ["Key: 'a', Value: '1'",  
# "Key: 'b', Value: '2'",  
# "Key: 'c', Value: '3'"]

Thanks!

4
{a: 1, b: 2, c: 3}.map { |key, value| "Key: '#{key}', Value: '#{value}'" }

=> ["Key: 'a', Value: '1'", "Key: 'b', Value: '2'", "Key: 'c', Value: '3'"]
2
h = {a: 1, b: 2, c: 3}
h.map{|k,v| "key: '#{k}' ,val: '#{v}'"}
# => ["key: 'a' ,val: '1'", "key: 'b' ,val: '2'", "key: 'c' ,val: '3'"]
1
  • Priti, thanks for all prompt and correct answers and good night! (in my country is 00:31, 21-07-2013) – Serg Ra6n Jul 20 '13 at 21:31
-1

You could always implement a struct:

struct keyItem
{
    char key[30];
    int value;
}

And then do something like this:

keyItem h[3] =
{
    { "a", 1 },
    { "b", 2 },
    { "c", 3 }
}

Your function like this:

void print_keys(keyItem[] k, int size)
{
    for (int i = 0; i < size; i++)
    {
        printf("Key: \"%s\", Value: '%d'\n", k[i].key, k[i].value);
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.