From: Dat Nguyen Date: 2001-09-13T03:26:44+09:00 Subject: [ruby-talk:21173] Re: @aHash{A..Z} = (0..25);



>From: David Alan Black
>Reply-To: ruby-talk@ruby-lang.org
>To: ruby-talk@ruby-lang.org (ruby-talk ML)
>Subject: [ruby-talk:21053] Re: @aHash{A..Z} = (0..25);
>Date: Tue, 11 Sep 2001 12:18:22 +0900
>
>Hello --
>
>On Tue, 11 Sep 2001, Dat Nguyen wrote:
>
> > How to write the following Perl code in Ruby:
> >
> > @aHash{A..Z} = (0..25);
>
>One possibility, drawn from some Ruby Behaviors experiments:
>
> class Hash
> alias :oldset :[]=
> def []=(ks,vs)
> ks.to_a.each_with_index do |k,i|
> oldset(k,vs.to_a[i])
> end
> end
> end
>
> c = {}
> c['A'..'Z'] = 0..25
>
>
>(One of my main incentives for working on Ruby Behaviors has
>always been to get more back-and-forth going between arrays (or
>ranges) and hashes.)
>
>
>David
>
>--
>David Alan Black
>home: dblack@candle.superlink.net
>work: blackdav@shu.edu
>Web: http://pirate.shu.edu/~blackdav

>

 

Study all solutions so far, I also come up with the following:
 
class Hash
    def Hash.array_array (index, value)
        aHash = {}
        index.each { |ind| aHash[ind] = value[index.index(ind)] }
        aHash
    end
end
 
aHash = Hash.array_array(('A'..'Z').to_a, (0..25).to_a)
 
This would declare and initialize a Hash out of any two parallel Arrays.
 
Dat


Get your FREE download of MSN Explorer at http://explorer.msn.com