Hello,
I want to have a string which, if in array, will be sorted like numbers.
I wrote this:
-----------------------------------------------------------------------------------------
class String2 < String
def <=> str2
self.to_i <=> str2.to_i
end
end
a = [ 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 `<=>': undefined method `to_i' for #<S:0x40020930 @a="10">
(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 = a
end
def <=> b
@a.is_a? String # >> true but..
@a.to_i <=> b.to_i # .. @a.to_i doesn't work if I don't define
to_i method below
end
def to_i
@a.to_i
end
def to_s
@a
end
end
a = [ String2.new('1'), String2.new('10'), String2.new('5') ]
puts a.sort.join(',')
-----------------------------------------------------------------------------------------
Thank you,
jan molic