From: google@... (Tom Payne) Date: 2003-01-20T22:13:44+09:00 Subject: Re: Feature request: Array.to_h dblack@candle.superlink.net wrote in message news:... > Almost :-) See . I seem to evade > naming any of the variants just "to_h" (they're to_h_raw, to_h_ikeys), > etc. I'm inclined to think "to_h" would be what I called "to_h_raw", > i.e.: [1,2,3,4].to_h => { 1 => 2, 3 => 4 }, but I'm not sure. I think of Arrays as mapping integers >= 0 to values, and of Hashes of mapping arbitrary keys to values. So, for me, the POLS for Array.to_h would be to produce a Hash that maps the same keys as the array to the same values, i.e [:a, :b].to_h => {0 => :a, 1 => b}. Your to_h ([1,2,3,4].to_h => { 1 => 2, 3 => 4 }) might be more familiar to a PERL programmer. IIRC, in PERL hashes can be written [key0, value0, key1, value1, ...], but I might be wrong. N.B. Your implementation of to_h_raw from : module Enumerable # The simplest to_h: array elements are taken two at a time. # (Not even indices -- just elements.) def to_h_raw a = dup h = {} h[a.shift] = a.shift || nil until a.empty? h end end should really be in the Array class, not the Enumerable module, because it uses the shift method: Arrays have this, but Enumerables don't. An implementation using each (provided by Enumerable): module Enumerable def to_h_raw(default = nil) result = Hash.new(default) key = nil index = 0 each do |element| case index % 2 when 0 then key = element when 1 then result[key] = element end index += 1 end result[key] = nil if index % 2 == 1 result end end [1, 2, 3, 4].to_h_raw => {1=>2, 3=>4} [1, 2, 3, 4, 5].to_h_raw => {5=>nil, 1=>2, 3=>4} Regards, Tom