get remaing characters in a string

C

Claus Guttesen

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
 
D

dblack

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?

You can index strings from the right with negative numbers:

"abcdef"[-3..-1] => "def"

I think that might be all you need.


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
 
C

Claus Guttesen

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
 
W

William James

Claus said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top