Extracting the Last N Characters from a Ruby String

Extracting the last n characters from a ruby string

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

Get last character in string

UPDATE:
I keep getting constant up votes on this, hence the edit. Using [-1, 1] is correct, however a better looking solution would be using just [-1]. Check Oleg Pischicov's answer.

line[-1]
# => "c"

Original Answer

In ruby you can use [-1, 1] to get last char of a string. Here:

line = "abc;"
# => "abc;"
line[-1, 1]
# => ";"

teststr = "some text"
# => "some text"
teststr[-1, 1]
# => "t"

Explanation:
Strings can take a negative index, which count backwards from the end
of the String, and an length of how many characters you want (one in
this example).

Using String#slice as in OP's example: (will work only on ruby 1.9 onwards as explained in Yu Hau's answer)

line.slice(line.length - 1)
# => ";"
teststr.slice(teststr.length - 1)
# => "t"

Let's go nuts!!!

teststr.split('').last
# => "t"
teststr.split(//)[-1]
# => "t"
teststr.chars.last
# => "t"
teststr.scan(/.$/)[0]
# => "t"
teststr[/.$/]
# => "t"
teststr[teststr.length-1]
# => "t"

what is the best way to remove the last n characters of a string (in Ruby)?

You can use ranges.

"string"[0..-4]

Ruby - How to select some characters from string

Try foo[0...100], any range will do. Ranges can also go negative. It is well explained in the documentation of Ruby.

Select all characters in a string until a specific character Ruby

You can avoid creating an unnecessary Array (like Array#split) or using a Regex (like Array#gsub) by using.

a = "2.452811139617034,42.10874821716908|3.132087902867818,42.028314077306646|-0.07934861041448178,41.647538468746916|-0.07948265046522918,41.64754863599606"

a[0,a.index('|')]
#=>"2.452811139617034,42.1087482171"

This means select characters at positions 0 up to the index of the first pipe (|). Technically speaking it is start at position 0 and select the length of n where n is the index of the pipe character which works in this case because ruby uses 0 based indexing.

As @CarySwoveland astutely pointed out the string may not contain a pipe in which case my solution would need to change to

#to return entire string
a[0,a.index('|') || a.size]
# or
b = a.index(?|) ? a[0,b] : a
# or to return empty string
a[0,a.index('|').to_i]
# or to return nil
a[0,a.index(?|) || -1]

Get first N characters from string without cutting the whole words


s = "Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world."
s = s.split(" ").each_with_object("") {|x,ob| break ob unless (ob.length + " ".length + x.length <= 70);ob << (" " + x)}.strip
#=> "Coca-Cola is the most popular and biggest-selling soft drink in"

How to mask all but last four characters in a string


positive lookahead

A positive lookahead makes it pretty easy. If any character is followed by at least 4 characters, it gets replaced :

"654321".gsub(/.(?=.{4})/,'#')
# "##4321"

Here's a description of the regex :

r = /
. # Just one character
(?= # which must be followed by
.{4} # 4 characters
) #
/x # free-spacing mode, allows comments inside regex

Note that the regex only matches one character at a time, even though it needs to check up to 5 characters for each match :

"654321".scan(r)
# => ["6", "5"]

/(.)..../ wouldn't work, because it would consume 5 characters for each iteration :

"654321".scan(/(.)..../)
# => [["6"]]
"abcdefghij".scan(/(.)..../)
# => [["a"], ["f"]]

If you want to parametrize the length of the unmasked string, you can use variable interpolation :

all_but = 4
/.(?=.{#{all_but}})/
# => /.(?=.{4})/

Code

Packing it into a method, it becomes :

def mask(string, all_but = 4, char = '#')
string.gsub(/.(?=.{#{all_but}})/, char)
end

p mask('testabcdef')
# '######cdef'
p mask('1234')
# '1234'
p mask('123')
# '123'
p mask('x')
# 'x'

You could also adapt it for sentences :

def mask(string, all_but = 4, char = '#')
string.gsub(/\w(?=\w{#{all_but}})/, char)
end

p mask('It even works for multiple words')
# "It even #orks for ####iple #ords"

Some notes about your code

string.to_s

Naming things is very important in programming, especially in dynamic languages.

string.to_s

If string is indeed a string, there shouldn't be any reason to call to_s.

If string isn't a string, you should indeed call to_s before gsub but should also rename string to a better description :

object.to_s
array.to_s
whatever.to_s

join

puts array.join(", ").delete(", ").inspect

What do you want to do exactly? You could probably just use join :

[1,2,[3,4]].join(", ").delete(", ")
# "1234"
[1,2,[3,4]].join
# "1234"

delete

Note that .delete(", ") deletes every comma and every whitespace, in any order. It doesn't only delete ", " substrings :

",a b,,,   cc".delete(', ')
# "abcc"
["1,2", "3,4"].join(', ').delete(', ')
# "1234"

Ruby, remove last N characters from a string?


Ruby 2.5+

As of Ruby 2.5 you can use delete_suffix or delete_suffix! to achieve this in a fast and readable manner.

The docs on the methods are here.

If you know what the suffix is, this is idiomatic (and I'd argue, even more readable than other answers here):

'abc123'.delete_suffix('123')     # => "abc"
'abc123'.delete_suffix!('123') # => "abc"

It's even significantly faster (almost 40% with the bang method) than the top answer. Here's the result of the same benchmark:

                     user     system      total        real
chomp 0.949823 0.001025 0.950848 ( 0.951941)
range 1.874237 0.001472 1.875709 ( 1.876820)
delete_suffix 0.721699 0.000945 0.722644 ( 0.723410)
delete_suffix! 0.650042 0.000714 0.650756 ( 0.651332)

I hope this is useful - note the method doesn't currently accept a regex so if you don't know the suffix it's not viable for the time being. However, as the accepted answer (update: at the time of writing) dictates the same, I thought this might be useful to some people.

How do I remove the last line of a string that has visible characters in ruby?

Consider a string like the following (line breaks written as \n):

str = "Hello\nThere\nWorld!\n\n"

First, use String#strip to remove trailing whitespace, and use String#split to break the string into an array where each element represents one line of the string.

str = str.strip.split("\n")
#=> ["Hello", "There", "World!"]

You can then extract the last line from the last element in the array using Array#pop.

last_line = str.pop
#=> "World!"

Finally, use Array#join to re-assemble the array.

str = str.join("\n")
#=> "Hello\nThere"


Related Topics



Leave a reply



Submit