W
warren ferguson
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=
=2C ordered from lsb at index 0 to msb at the highest index=2C so
"10011" as a string would be [1=2C1=2C0=2C0=2C1] as an Bitvector. Here's wh=
at I tried:
=20
class Bitvector < Array
def initialize(*)
@a =3D super
end
def to_s
# convert Bitvector=2C ordered lsb to msb=2C
# to string of 0s and 1s=2C 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=2C ordered msb to lsb=2C
# to Bitvector=2C ordered lsb to msb
Bitvector.new(self.reverse.split(//)).map{|k| k.to_i(2)}
end
end
# ----------------------------
v =3D "10011".to_bv
puts "v.class =3D #{v .class}"
puts "v =3D #{v}"
puts "--"
=20
v =3D Bitvector.new([0=2C1])
puts "v.class =3D #{v .class}"
puts "v =3D #{v}"
=20
The output from this program is
=20
v.class =3D Array
v =3D [1=2C 1=2C 0=2C 0=2C 1]
--
v.class =3D Bitvector
v =3D 10
What I don't understand is why the first part reports v is of class Array=
=2C instead of class Bitvector.
=20
Thanks=2C Warren =
of the Array class called Bitvector. A bit vector is an array of 0s and 1s=
=2C ordered from lsb at index 0 to msb at the highest index=2C so
"10011" as a string would be [1=2C1=2C0=2C0=2C1] as an Bitvector. Here's wh=
at I tried:
=20
class Bitvector < Array
def initialize(*)
@a =3D super
end
def to_s
# convert Bitvector=2C ordered lsb to msb=2C
# to string of 0s and 1s=2C 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=2C ordered msb to lsb=2C
# to Bitvector=2C ordered lsb to msb
Bitvector.new(self.reverse.split(//)).map{|k| k.to_i(2)}
end
end
# ----------------------------
v =3D "10011".to_bv
puts "v.class =3D #{v .class}"
puts "v =3D #{v}"
puts "--"
=20
v =3D Bitvector.new([0=2C1])
puts "v.class =3D #{v .class}"
puts "v =3D #{v}"
=20
The output from this program is
=20
v.class =3D Array
v =3D [1=2C 1=2C 0=2C 0=2C 1]
--
v.class =3D Bitvector
v =3D 10
What I don't understand is why the first part reports v is of class Array=
=2C instead of class Bitvector.
=20
Thanks=2C Warren =