M
MiG
Hello,
I want to have a string which, if in array, will be sorted like numbers=
=20
I wrote this:
-------------------------------------------------------------------------=
----------------
class String2 < String
def <=3D> str2
self.to_i <=3D> str2.to_i
end
end
a =3D [ String2.new('1'), String2.new('10'), String2.new('5') ]
puts a.sort.join(',')
-------------------------------------------------------------------------=
----------------
It produces "1,10,5", but I expected "1,5,10"
Then I wrote a class without String inheritance and it works.
BUT: another strange thing happened:
in `<=3D>': undefined method `to_i' for #<S:0x40020930 @a=3D"10"> =20
(NoMethodError)
to_i method, even if @a is a String, must be explicitely defined.
Moreover "defined". What do you think about it?
-------------------------------------------------------------------------=
----------------
class String2
def initialize a
@a =3D a
end
def <=3D> b
@a.is_a? String # >> true but..
@a.to_i <=3D> b.to_i # .. @a.to_i doesn't work if I don't defin=
e =20
to_i method below
end
def to_i
@a.to_i
end
def to_s
@a
end
end
a =3D [ String2.new('1'), String2.new('10'), String2.new('5') ]
puts a.sort.join(',')
-------------------------------------------------------------------------=
I want to have a string which, if in array, will be sorted like numbers=
=20
I wrote this:
-------------------------------------------------------------------------=
----------------
class String2 < String
def <=3D> str2
self.to_i <=3D> str2.to_i
end
end
a =3D [ String2.new('1'), String2.new('10'), String2.new('5') ]
puts a.sort.join(',')
-------------------------------------------------------------------------=
----------------
It produces "1,10,5", but I expected "1,5,10"
Then I wrote a class without String inheritance and it works.
BUT: another strange thing happened:
in `<=3D>': undefined method `to_i' for #<S:0x40020930 @a=3D"10"> =20
(NoMethodError)
to_i method, even if @a is a String, must be explicitely defined.
Moreover "defined". What do you think about it?
-------------------------------------------------------------------------=
----------------
class String2
def initialize a
@a =3D a
end
def <=3D> b
@a.is_a? String # >> true but..
@a.to_i <=3D> b.to_i # .. @a.to_i doesn't work if I don't defin=
e =20
to_i method below
end
def to_i
@a.to_i
end
def to_s
@a
end
end
a =3D [ String2.new('1'), String2.new('10'), String2.new('5') ]
puts a.sort.join(',')
-------------------------------------------------------------------------=