I'm a Perl developer trying to learn Ruby...
So, I'll demonstrate in Perl what I'm trying to accomplish in Ruby and then summarize at the end...
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
# Given the following data structure (an array of hashes)
my $j = [
{
id => 1,
key1 => 'name1',
key2 => 'data',
key3 => 'data',
key4 => 'foo',
},
{
id => 2,
key1 => 'name1',
key2 => 'data',
key3 => 'data',
key4 => 'bar',
},
{
id => 3,
key1 => 'name2',
key2 => 'data',
key3 => 'data',
key4 => 'baz',
},
];
print ~~@$j,"\n";
print Dumper($j)."\n";
my $myHash; # make it a reference to a hoa.
for my $array ( @{$j} )
{
# the key to my new key-name is always known
push(@{$myHash->{$array->{key1}}},$array->{key4});
}
print Dumper($myHash)."\n";
And the output:
Initial array:
$VAR1 = [
{
'key2' => 'data',
'key4' => 'foo',
'key1' => 'name1',
'id' => 1,
'key3' => 'data'
},
{
'key2' => 'data',
'key4' => 'bar',
'key1' => 'name1',
'id' => 2,
'key3' => 'data'
},
{
'key2' => 'data',
'key4' => 'baz',
'key1' => 'name2',
'id' => 3,
'key3' => 'data'
}
];
What I'm trying to get:
$VAR1 = {
'name2' => [
'baz'
],
'name1' => [
'foo',
'bar'
]
};
...and I'm trying to do it in as succinct code as possible, which has proven to be a pain given my lack of Ruby goodness. I've tried multiple attempts at this including several tries at map similar to the same code structure I used in Perl to no avail.
That said, I did find the following snippet, just now, which almost works but I'm sure I'm doing something wrong...
h = Hash[j.collect {|array| [array.key1,array.key4] }]
This gets me the right hash key but it doesn't push the key4 value into an array of the hash. Still looking but some nudge in the right direction would be appreciated. If I find the answer before getting an answer here, I'll answer the question for the edification of future readers.
EDIT!
I need to clarify something that I just figured out and is probably the wrench in my clock. The data that I'm getting is not a pure array. It's actually an object from DataMapper.