Triming characters from the front of a String...

S

sketchitup

For the life of me I can't figure out an easy way to remove the first
couple of characters from a String. I looked in my Ruby book, searched
online, and checked the documentation for the String class. I must be
missing something obvious.

Could someone let me know if there is a method that I can use to do
this, or if there is some other trick to it.

Thanks,

The SketchUp Artist
 
F

Florian Gross

For the life of me I can't figure out an easy way to remove the first
couple of characters from a String. I looked in my Ruby book, searched
online, and checked the documentation for the String class. I must be
missing something obvious.

To remove all whitespace:
" hello world".lstrip # => "hello world"

To remove the first n characters (destructively):
str = "hello world"
str.slice!(0, 5) # => "hello"
str # => " world"
 
S

Sebastian Hungerecker

For the life of me I can't figure out an easy way to remove the first
couple of characters from a String. I looked in my Ruby book, searched
online, and checked the documentation for the String class. I must be
missing something obvious.

Could someone let me know if there is a method that I can use to do
this, or if there is some other trick to it.

str[x..-1] gives you str without the first x characters.


HTH,
Sebastian
 
S

sketchitup

For the life of me I can't figure out an easy way to remove the first
couple of characters from a String. I looked in my Ruby book, searched
online, and checked the documentation for the String class. I must be
missing something obvious.
Could someone let me know if there is a method that I can use to do
this, or if there is some other trick to it.

str[x..-1] gives you str without the first x characters.

HTH,
Sebastian

That is just what I needed.

Thank you Sebastian and Florian
 
P

Phrogz

For the life of me I can't figure out an easy way to remove the first
couple of characters from a String. I looked in my Ruby book, searched
online, and checked the documentation for the String class. I must be
missing something obvious.
str[x..-1] gives you str without the first x characters.

And
str[0..4]=''
will replace the first 5 characters in the string with an empty
string.

Likewise
str.sub!( /\A.{5}/m, '' )
will mutate the original string to replace the first 5 characters with
an empty string.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top