Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting the last n characters from a ruby string

Tags:

string

ruby

To get the last n characters from a string, I assumed you could use

ending = string[-n..-1] 

but if the string is less than n letters long, you get nil.

What workarounds are available?

Background: The strings are plain ASCII, and I have access to ruby 1.9.1, and I'm using Plain Old Ruby Objects (no web frameworks).

like image 665
Andrew Grimm Avatar asked Feb 01 '10 05:02

Andrew Grimm


People also ask

How do you get the last n characters of a string?

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.

How do you get the last character of a string in Ruby?

Getting the last character To access the last character of a string, we need to pass the negative index -1 to the square brackets [] in Ruby. Note: Negative index gets the data from the end of a string.

How do you get the first n characters of a string in Ruby?

To access the first n characters of a string in ruby, we can use the square brackets syntax [] by passing the start index and length. In the example above, we have passed the [0, 3] to it. so it starts the extraction at index position 0 , and extracts before the position 3 .

What does \n do in Ruby?

In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .


2 Answers

Well, the easiest workaround I can think of is:

ending = str[-n..-1] || str 

(EDIT: The or operator has lower precedence than assignment, so be sure to use || instead.)

like image 108
perimosocordiae Avatar answered Nov 23 '22 04:11

perimosocordiae


Here you have a one liner, you can put a number greater than the size of the string:

"123".split(//).last(5).to_s 

For ruby 1.9+

"123".split(//).last(5).join("").to_s 

For ruby 2.0+, join returns a string

"123".split(//).last(5).join 
like image 26
Gareve Avatar answered Nov 23 '22 05:11

Gareve