Hash from two arrays: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 2: Line 2:


Using two Arrays of equal length, create a Hash object where the elements from on array (the keys) are linked to the elements of the other (the values)
Using two Arrays of equal length, create a Hash object where the elements from on array (the keys) are linked to the elements of the other (the values)

==[[Perl]]==
'''Interpreter:''' [[Perl]] 5.8.8

Short

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
@hash{@keys} = @vals;

Mid Length

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
$hash{$keys[$_]} = $vals[$_] for (0 .. $#keys);

Long

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
foreach my $idx (0..$#keys){
$hash{$keys[$idx]} = $vals[$idx];
}


==[[Ruby]]==
==[[Ruby]]==

Revision as of 20:30, 22 January 2007

Task
Hash from two arrays
You are encouraged to solve this task according to the task description, using any language you may know.

Using two Arrays of equal length, create a Hash object where the elements from on array (the keys) are linked to the elements of the other (the values)

Perl

Interpreter: Perl 5.8.8

Short

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
@hash{@keys} = @vals;

Mid Length

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
$hash{$keys[$_]} = $vals[$_] for (0 .. $#keys);

Long

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
foreach my $idx (0..$#keys){
  $hash{$keys[$idx]} = $vals[$idx];
}

Ruby

 ary_keys=['hal',666,[1,2,3]]
 ary_vals=['ibm','devil',123]
 hash={}
 (0...3).each do |ix|
   hash[ary_keys[ix]]=ary_vals[ix]
 end
 #hash => {'hal' => 'ibm', 666 => 'devil', [1,2,3] => 123}
 #retrieve the value linked to the key [1,2,3]
 puts hash[ [1,2,3] ]
 #123