[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: array to hash

dblack

3/20/2007 11:43:00 AM

Hi --

On 3/20/07, Servando Garcia <garcia.servando@gmail.com> wrote:
>
> Hello all
> Is there a method to collect the items in an array into a hash
>
> I want to go from this X =[1,2,3,4,5,6] to this Y={1 =>2, 3 =>4, 5 =>6}

Hash[*X]


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning...)
(See what readers are saying! http://www.r.../r...)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.r...)

2 Answers

dblack

3/20/2007 2:37:00 PM

0

Hi --

On 3/20/07, Servando Garcia <garcia.servando@gmail.com> wrote:
>
> David
> No Way that is to easy. My new question to you is how does this work.

The 'unarray' operator * turns an array into a list. So in effect you're doing:

Hash[1,2,3,4,5,6]


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning...)
(See what readers are saying! http://www.r.../r...)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.r...)

Martin DeMello

3/20/2007 2:40:00 PM

0

On 3/20/07, Servando Garcia <garcia.servando@gmail.com> wrote:
>
> David
> No Way that is to easy. My new question to you is how does this work.
> Where can I read the source code for this method

It's a combination of two things:

1. Hash.[] creates a hash from a comma separated even-length list

Hash[1,2,3,4,5,6] # => { 1=>2, 3=>4, 5=>6 }

2. *ary converts an array into a comma-separated list

def foo(a, b=nil, c=nil)
p a
p b
p c
end

ary = [1,2,3]

def foo(a, b=nil, c=nil)
p a
p b
p c
end

ary = [1,2,3]

irb> foo(ary)
[1, 2, 3]
nil
nil
=> nil
irb> foo(*ary)
1
2
3
=> nil

martin