Reputation: 23
need to be able to take the last line of a string and put it in it's own string. and then more importantly I need to be able to remove the last line of the original string that has non-whitespace characters.
Upvotes: 2
Views: 1340
Reputation: 8777
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"
Upvotes: 3