From: "David A. Black" Date: 2010-08-08T08:12:00+09:00 Subject: Re: question about sub-class of array Hi -- On Sun, 8 Aug 2010, warren ferguson wrote: > > I don't understand why thsi isn't working. I wanted to introduce a subclass of the Array class called Bitvector. A bit vector is an array of 0s and 1s, ordered from lsb at index 0 to msb at the highest index, so > "10011" as a string would be [1,1,0,0,1] as an Bitvector. Here's what I tried: > > class Bitvector < Array > def initialize(*) > @a = super > end > def to_s > # convert Bitvector, ordered lsb to msb, > # to string of 0s and 1s, ordered msb to lsb > @a.map{|i| i.to_s(2)}.reverse.join > end > end > class String > def to_bv > # convert bit string of 0s and 1s, ordered msb to lsb, > # to Bitvector, ordered lsb to msb > Bitvector.new(self.reverse.split(//)).map{|k| k.to_i(2)} > end > end > # ---------------------------- > v = "10011".to_bv > puts "v.class = #{v .class}" > puts "v = #{v}" > puts "--" > > v = Bitvector.new([0,1]) > puts "v.class = #{v .class}" > puts "v = #{v}" > > The output from this program is > > v.class = Array > v = [1, 1, 0, 0, 1] > -- > v.class = Bitvector > v = 10 > > What I don't understand is why the first part reports v is of class Array, instead of class Bitvector. It's because of the map operation, which returns an Array. David -- David A. Black, Senior Developer, Cyrus Innovation Inc. The Ruby training with Black/Brown/McAnally Compleat Philadelphia, PA, October 1-2, 2010 Rubyist http://www.compleatrubyist.com