Forum: Ruby Triming characters from the front of a String...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2007-07-27 18:43
(Received via mailing list)
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
Florian G. (Guest)
on 2007-07-27 18:56
(Received via mailing list)
> 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"
Sebastian H. (Guest)
on 2007-07-27 19:14
(Received via mailing list)
removed_email_address@domain.invalid wrote:
> 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
(Guest)
on 2007-07-27 19:57
(Received via mailing list)
On Jul 27, 8:13 am, Sebastian H. <removed_email_address@domain.invalid>
wrote:
>
> HTH,
> Sebastian
> --
> NP: Kreator - Fatal Energy
> Ist so, weil ist so
> Bleibt so, weil war so

That is just what I needed.

Thank you Sebastian and Florian
Gavin K. (Guest)
on 2007-07-27 20:01
(Received via mailing list)
On Jul 27, 9:13 am, Sebastian H. <removed_email_address@domain.invalid>
wrote:
> removed_email_address@domain.invalid wrote:
> > 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.
This topic is locked and can not be replied to.