Hi Chris,
> [[A, B, C][1,2,3]]
>
> I can easily make a hash (using each.with_index) where one value is
> the lookup value for the other value:
I'd consider zip for this:
a = [['a', 'b', 'c'], [1,2,3]]
h = Hash.new
a[1].zip(a[0]) {|key, value| h[key] = value}
p h # {1=>"a", 2=>"b", 3=>"c"}
> Now suppose I have a AoA like
>
> [[A, B, C,][1,2,2]]
>
> Is there a readable way...
I don't know that it's particularly readable, but:
a = [['a', 'b', 'c'], [1,2,2]]
h = Hash.new
a[1].zip(a[0]) do |key, value|
case h[key]
when NilClass
h[key] = value
when Array
h[key] << value
else
h[key] = [h[key], value]
end
end
p h # {1=>"a", 2=>["b", "c"]}
If you allow 1=>["a"] it gets a lot easier:
a = [['a', 'b', 'c'], [1,2,2]]
h = Hash.new {|hash, key| hash[key] = []}
a[1].zip(a[0]) {|key, value| h[key] << value}
p h # {1=>["a"], 2=>["b", "c"]}
Wayne
On 11/30/05, Chris McMahon <[EMAIL PROTECTED]> wrote:
> Hi all....
>
> Again, apologies for the OT, stop me if it's not amusing...
>
> Suppose I have an array of arrays like
>
> [[A, B, C][1,2,3]]
>
> I can easily make a hash (using each.with_index) where one value is
> the lookup value for the other value:
>
> 1=>A
> 2=>B
> 3=>C
>
> Now suppose I have a AoA like
>
> [[A, B, C,][1,2,2]]
>
> Is there a readable way to construct a hash like
>
> 1=>A
> 2=>[B, C]
>
> ?
>
> Thanks,
> -Chris
>
> _______________________________________________
> Wtr-general mailing list
> [email protected]
> http://rubyforge.org/mailman/listinfo/wtr-general
>
_______________________________________________
Wtr-general mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/wtr-general