Hi –
On 3/20/07, Servando G. [email protected] wrote:
Hello all
Is there a method to collect the items in an array into a hashI want to go from this X =[1,2,3,4,5,6] to this Y={1 =>2, 3 =>4, 5 =>6}
Hash[*X]
David
On 3/20/07, Servando G. [email protected] wrote:
Sam
Try this
arr = [1,2,3,4,5,6]
ahash = Hash[*arr]
p arr
p ahash
Harry
–
http://www.kakueki.com/ruby/list.html
Japanese Ruby List Subjects in English
On 20 mars 07, at 12:53, Servando G. wrote:
Where can I read the source code for this method ?
<http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/trunk/hash.c?
revision=11708&view=markup>
The function you are looking for is ‘rb_hash_s_create’.
Hi –
On 3/20/07, Servando G. [email protected] 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
def to_h(&block)
Hash[*self.collect { |v|
[v, block.call(v)]
}.flatten]
end
end
On Tue, Mar 20, 2007 at 08:33:09PM +0900, Servando G. wrote:
I want to go from this X =[1,2,3,4,5,6] to this Y={1 =>2, 3 =>4, 5 =>6}Just seems like there should be oneThanks in advanceSam
I’m glad you got the answer you were seeking. I have a request, though:
Please provide plain text email content in the future. Some of us
(intentionally) avoid HTML email.
On 3/20/07, Servando G. [email protected] 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:
- Hash.[] creates a hash from a comma separated even-length list
Hash[1,2,3,4,5,6] # => { 1=>2, 3=>4, 5=>6 }
- *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