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!

3 Answers 3

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'"]
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Priti, thanks for all prompt and correct answers and good night! (in my country is 00:31, 21-07-2013)
-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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.