Generate from two ruby arrays an appropriate JSON output

I have two simple ruby arrays and a JSON string mapping the elements of the first array to the elements of the second array:

keys = [:key0, :key1, :key2]
values = [:value0, :value1, :value2]

jsonString = {keys[0] => values[0], keys[1] => values[1], keys[2] => values[2]} 

Writing this to a file:

file.write(JSON.pretty_generate(jsonString))

results into a nicely printed json object:

{
    "key0": "value0",
    "key1": "value1",
    "key2": "value2"
}

But how can I generate the same output of two much bigger arrays without listing all these elements explicitly?

I just need something like

jsonString = {keys => values}

but this produces a different output:

{
    "[:key0, :key1, :key2]":
    [
        "value0",
        "value1",
        "value2"
    ]
}

How can I map the two without looping over both?

Answers


Use Array#zip to make pairs of values and then make hash of them:

keys = [:key0, :key1, :key2]
values = [:value0, :value1, :value2]
Hash[keys.zip values]
# => {:key0=>:value0, :key1=>:value1, :key2=>:value2}

array = keys.zip(values)
#=> [[:key0, :value0], [:key1, :value1], [:key2, :value2]]

Array#zip merges elements of self to the corresponding elements of the argument array and you get an array of arrays. This you can convert into a hash ...

hash = array.to_h
# => {:key0=>:value0, :key1=>:value1, :key2=>:value2}

... and the hash you can turn into a json string.

jsonString = JSON.pretty_generate(hash)
puts jsonString
#{
#  "key0": "value0",
#  "key1": "value1",
#  "key2": "value2"
#}

Need Your Help

Control the width of the column bar in a chart c#

c# mschart

I am using a MS chart for displaying some information and i have to show different charts when the user clicks a bar. All that works totally fine. but the width is totally out of my control. It looks

What are alternatives to SQL database storage for a web site?

php sql cgi lamp

An SQL database is overkill if your storage needs are small. When I was young and dumb, I used a text file and flock()ed it when I needed to access it. This doesn't scale, but I still feel that non-