[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

get remaing characters in a string

Claus Guttesen

1/7/2007 12:22:00 AM

Hi.

I need to get the last three characters in a string. I couldn't find a
function in the String class so I came up with this:

class Remainder

attr_writer :n

def initialize(t = "", n = 0)
@t = t.to_s
@n = n.to_i
end

def get
get_remaining_letters
end

private
def get_remaining_letters
s = @t.size
if s < @n
r = 0
else
r = s - @n
end

ft = @t.slice(r, @n)
end

end


t = Remainder.new("Guttesen", 5)
puts t.get
tesen
t.n = 4
puts t.get
esen

Did I reinvent the wheel or does it make sense to add it to String?

regards
Claus

4 Answers

Daniel Finnie

1/7/2007 12:27:00 AM

0

You can use String#[] with a Range instead:
>> "asdfhsdfabc"[-3..-1]
=> "abc"

or you can specify the length:
>> "asdfhsdfabc"[-3, 3]
=> "abc"

Negative numbers count from the end of the string. So basically the
strings length plus your negative number is the position from the start
of the string.

Dan

Claus Guttesen wrote:
> Hi.
>
> I need to get the last three characters in a string. I couldn't find a
> function in the String class so I came up with this:
>
> class Remainder
>
> attr_writer :n
>
> def initialize(t = "", n = 0)
> @t = t.to_s
> @n = n.to_i
> end
>
> def get
> get_remaining_letters
> end
>
> private
> def get_remaining_letters
> s = @t.size
> if s < @n
> r = 0
> else
> r = s - @n
> end
>
> ft = @t.slice(r, @n)
> end
>
> end
>
>
> t = Remainder.new("Guttesen", 5)
> puts t.get
> tesen
> t.n = 4
> puts t.get
> esen
>
> Did I reinvent the wheel or does it make sense to add it to String?
>
> regards
> Claus
>
>

dblack

1/7/2007 12:29:00 AM

0

Claus Guttesen

1/7/2007 12:37:00 AM

0

> > I need to get the last three characters in a string. I couldn't find a
> > function in the String class so I came up with this:
> >
> You can index strings from the right with negative numbers:
>
> "abcdef"[-3..-1] => "def"
>
> I think that might be all you need.

I see. Thank you very much for all the replies.

regards
Claus

William James

1/7/2007 8:15:00 AM

0

Claus Guttesen wrote:
> Hi.
>
> I need to get the last three characters in a string. I couldn't find a
> function in the String class so I came up with this:
>
> class Remainder
>
> attr_writer :n
>
> def initialize(t = "", n = 0)
> @t = t.to_s
> @n = n.to_i
> end
>
> def get
> get_remaining_letters
> end
>
> private
> def get_remaining_letters
> s = @t.size
> if s < @n
> r = 0
> else
> r = s - @n
> end
>
> ft = @t.slice(r, @n)
> end
>
> end
>
>
> t = Remainder.new("Guttesen", 5)
> puts t.get
> tesen
> t.n = 4
> puts t.get
> esen
>
> Did I reinvent the wheel or does it make sense to add it to String?
>
> regards
> Claus

If the length of the string is less than 3,
the entire string will be returned.

s = "ab"
s[ /.{0,3}$/ ]
s[-3,3] || s