[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Hash#each with nested array as value

Earle Clubb

10/17/2007 3:46:00 PM

I have a hash where the values are nested arrays. I'd like to be able to
iterate over the hash and have 3 vars available in the block: key,
value[0], and value[1]. As you can see, h.each {|a,b,c|...} doesn't
work. Is there a better way to do it than the last line below? Thanks.

Earle

--------------------

irb(main):001:0> require 'pp'
=> true
irb(main):002:0> h = {0 => [[1], [2]]}
=> {0=>[[1], [2]]}
irb(main):003:0> h.each {|a, b| pp a, b}
0
[[1], [2]]
=> {0=>[[1], [2]]}
irb(main):004:0> h.each {|a, b, c| pp a, b, c}
0
[[1], [2]]
nil
=> {0=>[[1], [2]]}
irb(main):005:0> h.each {|a, b| pp a, b[0], b[1]}
0
[1]
[2]
=> {0=>[[1], [2]]}

--------------------
--
Posted via http://www.ruby-....

3 Answers

Phrogz

10/17/2007 3:58:00 PM

0

On Oct 17, 9:45 am, Earle Clubb <ecl...@valcom.com> wrote:
> I have a hash where the values are nested arrays. I'd like to be able to
> iterate over the hash and have 3 vars available in the block: key,
> value[0], and value[1]. As you can see, h.each {|a,b,c|...} doesn't
> work.

Not much better, but:

irb(main):006:0> h = { :a => [:foo, :bar] }
=> {:a=>[:foo, :bar]}

irb(main):007:0> h.each{ |key,pair| a,b = *pair; p key, a, b }
:a
:foo
:bar

Gordon Thiesfeld

10/17/2007 4:05:00 PM

0

On 10/17/07, Earle Clubb <eclubb@valcom.com> wrote:
> I have a hash where the values are nested arrays. I'd like to be able to
> iterate over the hash and have 3 vars available in the block: key,
> value[0], and value[1]. As you can see, h.each {|a,b,c|...} doesn't
> work. Is there a better way to do it than the last line below? Thanks.
>
> Earle

Use parentheses.

>> h = [0 => [[1],[2]]}
>> h.each{|k,(a,b)| p k, a, b}
0
[1]
[2]
=> {0=>[[1], [2]]}

Regards,

Gordon
>>

Earle Clubb

10/17/2007 6:10:00 PM

0

Gordon Thiesfeld wrote:
> On 10/17/07, Earle Clubb <eclubb@valcom.com> wrote:
>> I have a hash where the values are nested arrays. I'd like to be able to
>> iterate over the hash and have 3 vars available in the block: key,
>> value[0], and value[1]. As you can see, h.each {|a,b,c|...} doesn't
>> work. Is there a better way to do it than the last line below? Thanks.
>>
>> Earle
>
> Use parentheses.
>
>>> h = [0 => [[1],[2]]}
>>> h.each{|k,(a,b)| p k, a, b}
> 0
> [1]
> [2]
> => {0=>[[1], [2]]}
>
> Regards,
>
> Gordon

Perfect. Thanks, Gordon.

Earle
--
Posted via http://www.ruby-....