T. Onoma
10/24/2004 4:08:00 PM
On Sunday 24 October 2004 09:52 am, Simon Strandgaard wrote:
| New implementation is here:
|
| class String
| def first(length=nil)
| length ||= 1
| unless length.respond_to?(:to_int)
| raise TypeError, "cannot convert #{length.class} to Integer"
| end
| n = length.to_int
| unless n.kind_of?(Integer)
| raise TypeError, "#{length.class}#to_int should return Integer"
| end
| raise ArgumentError, "negative string size" if n < 0
| n = [n, self.size].min
| self[0, n]
| end
| def last(length=nil)
| length ||= 1
| unless length.respond_to?(:to_int)
| raise TypeError, "cannot convert #{length.class} to Integer"
| end
| n = length.to_int
| unless n.kind_of?(Integer)
| raise TypeError, "#{length.class}#to_int should return Integer"
| end
| raise ArgumentError, "negative string size" if n < 0
| n = [n, self.size].min
| self[-n, n]
| end
| end
|
|
|
|
| btw: Is this better?
Yes, I think so, but this might be even more so,
begin
n = length.to_int
rescue NoMethodError
raise TypeError, "cannot convert #{length.class} to Integer"
end
also
| unless n.kind_of?(Integer)
| raise TypeError, "#{length.class}#to_int should return Integer"
| end
I don't think this is really needed, since such a bug would be worked out else
where. (That #to_int might be used usefully for something other then
returning an integer is extremely unlikely and thus not worth the check).
T.