[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Array Merging into Hash

Bucco

5/29/2006 10:56:00 PM

Is there a simple way of merging two arrays into one has with one array
being the keys and the other being the values for the has?
a = [1, 2, 3']
b = ['a', 'b', 'c']
h = {1=>'a', 2=>'b', 3=>'c'}

Thanks:)
SA

4 Answers

gabriele renzi

5/29/2006 11:03:00 PM

0

Bucco ha scritto:
> Is there a simple way of merging two arrays into one has with one array
> being the keys and the other being the values for the has?
> a = [1, 2, 3']
> b = ['a', 'b', 'c']
> h = {1=>'a', 2=>'b', 3=>'c'}


>> a=[1,2,3]
=> [1, 2, 3]
>> b=[:a,:b,:c]
=> [:a, :b, :c]
>> Hash[*a.zip(b).flatten]
=> {1=>:a, 2=>:b, 3=>:c}

Marcin Mielzynski

5/29/2006 11:04:00 PM

0

Bucco wrote:
> Is there a simple way of merging two arrays into one has with one array
> being the keys and the other being the values for the has?
> a = [1, 2, 3']
> b = ['a', 'b', 'c']
> h = {1=>'a', 2=>'b', 3=>'c'}

a = [1, 2, 3]
b = ['a', 'b', 'c']
p a.zip(b).inject({}){|h,(k,v)| h[k]=v;h}


lopex

Bucco

5/29/2006 11:20:00 PM

0

Thank you.
:)
SA

Robert Klemme

5/30/2006 7:12:00 AM

0

Marcin MielżyÅ?ski wrote:
> Bucco wrote:
>> Is there a simple way of merging two arrays into one has with one array
>> being the keys and the other being the values for the has?
>> a = [1, 2, 3']
>> b = ['a', 'b', 'c']
>> h = {1=>'a', 2=>'b', 3=>'c'}
>
> a = [1, 2, 3]
> b = ['a', 'b', 'c']
> p a.zip(b).inject({}){|h,(k,v)| h[k]=v;h}

Even more efficient:

>> require 'enumerator'
=> true
>> a = [1, 2, 3]
=> [1, 2, 3]
>> b = ['a', 'b', 'c']
=> ["a", "b", "c"]
>> a.to_enum(:zip,b).inject({}) {|h,(k,v)| h[k]=v; h}
=> {1=>"a", 2=>"b", 3=>"c"}

Kind regards

robert