I have a hashes like this
name = ['Jhon Doe', 'Jane Doe' , 'David']
role = ['Admin', 'Accountant', 'Sales']
i want to make it look like this
data = [
{name => 'Jhon Doe', role => 'Admin'},
{name => 'Jane Doe', role => 'Accountan'},
{name => 'David', role => 'Sales'}
]
is it posible to do something like this?
CodePudding user response:
You can achieve desired result using product
and transpose
:
[[:name].product(name), [:role].product(role)].transpose.map(&:to_h)
Probably, a more elegant solution would be using map
and with_index
:
name.map.with_index { |name_i, index| { name: name, role: role[index] } }
CodePudding user response:
Here's a rather simple solution:
name.zip(role).map {|name, role| { name:, role: }}
#=> [
# { name: 'Jhon Doe', role: 'Admin' },
# { name: 'Jane Doe', role: 'Accountant' },
# { name: 'David', role: 'Sales' }
# ]
CodePudding user response:
here name and role should be an array
, not hash
name = ['Jhon Doe', 'Jane Doe' , 'David']
role = ['Admin', 'Accountant', 'Sales']
you can use the below to generate the output hash
my_hash_array = []
name.size.times{|i| my_hash_array << {name: name[i], role: role[i]} }
I hope this will help you.