Generat a hash from 2 arrays ala Perl

In Perl you can generate a hash from key and value arrays as
%hash{@keys}=(@values).
Also %hash = qw/ a 1 b 2 c 3/.
How are these things done in Ruby?
So far many things I’ve tried in irb failed.

Thanks,
Mike

clés = [‘hal’, 666, [1,2,3]]
vals = [‘ibm’, ‘devil’, 123]

hash = clés.zip(vals).to_h
p hash

Thank you sir,
I failed to mention that I’m limited to Ruby 1.9.3 and the Array.to_h post dates that. I’ve also tried Hash.try_convert with no luck.
The best I’ve come up with is:
hash={}
keys = %w/a b c/
values = *(1…3)
(0…keys.length).each{ |i| hash[ keys[i] ] = values[i] }
I’ve yet to concoct anything that will turn [‘a’,1,‘b’,2,‘c’,3] into a hash.
Thank you for the effort anyway.
BTW, are you kin to Isaac Asimov? I’ve read many of his books.
Ciao

I am a huge fan of him. And everything related to AI.

Here an older method to do it:

clés = [‘hal’,666,[1,2,3]]
vals = [‘ibm’,‘devil’,123]

hash = Hash[clés.zip(vals)]

p hash # => {“hal” => “ibm”, 666 => “devil”, [1, 2, 3] => 123}

#récupérer la valeur liée à la clé [1,2,3]
puts hash[ [1,2,3] ] # => 123

That’s more elegant than anything else I’ve seen I’ll be adopting it.
Thank you.
Mike

Mike, since I’ve seen you put quite a few posts up, you might want to know that you can get your code formatted by indenting it four spaces. E.g.:

%hash{@keys}=(@values)

For other tricks you can use, see this markdown cheat sheet.

Bob,
I’ve been using indentation for decades in my code but who ever built this website removes my indentation and what they do to links should be considered a sin.
BTW, I put spaces at the beginning of this line but you’ll never see them.
Thanks for the ‘cheat sheet’, I’ll take a look.
Mike

This site is markdown-based, as are many these days. It will also accept HTML tags. I’ve been around for a long time as you have, and I must say that once I got used to markdown I liked it a great deal.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs