Skip to content

Instantly share code, notes, and snippets.

@notbenh
Created May 18, 2013 22:50
Show Gist options
  • Save notbenh/5606012 to your computer and use it in GitHub Desktop.
Save notbenh/5606012 to your computer and use it in GitHub Desktop.
If I had a list of arrays, and I wanted each element of these arrays to be keys with the array as the value. I can do this in perl but how do I do that in ruby? Seems that this is a syntax error: {[%w[a b c],%w[x y z]].each{|a| a.each{|v| v=>a}}}
use strict;
use warnings;
use Data::Dumper;
=head1 GOAL
two arrays ['a','b','c'] and ['x','y','z']
become a hash:
{ a => ['a','b','c']
, b => ['a','b','c']
, c => ['a','b','c']
, x => ['x','y','z']
, y => ['x','y','z']
, z => ['x','y','z']
}
=cut
print Dumper({ map{my $a=$_;map{$_=>$a} @$a} [qw{a b c}], [qw{x y z}] });
__END__
$VAR1 = {
'y' => [
'x',
'y',
'z'
],
'c' => [
'a',
'b',
'c'
],
'a' => $VAR1->{'c'},
'b' => $VAR1->{'c'},
'x' => $VAR1->{'y'},
'z' => $VAR1->{'y'}
};
@nicklewis
Copy link

[%w[a b c], %w[x y z]].inject({}) do |h,ary|
  ary.inject(h) do |h,x|
    h.merge(x => ary)
  end
end

@notbenh
Copy link
Author

notbenh commented May 18, 2013

Ahhh... so extra steps are required! Awesome thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment