tags:

views:

342

answers:

4
One\n
Two\n
Three\n
Four\n

remove_lines(2) would remove the first two lines, leaving the string:

Three\n
Four\n
+6  A: 
class String

  def remove_lines(i)
    split("\n")[i..-1].join("\n")
  end

end

Calling "One\nTwo\nThree\nFour\n".remove_lines(2) would result in "Three\nFour". If you need the trailing "\n" you need to extend this method accordingly.

Koraktor
Wouldn't the method keep empty lines as-is?
musicfreak
Really fast ;). Checked this a minute ago. You're right.
Koraktor
+10  A: 

s.to_a[2..-1].join

>> s = "One\nTwo\nThree\nFour\n"
=> "One\nTwo\nThree\nFour\n"
>> s.to_a[2..-1].join
=> "Three\nFour\n"
DigitalRoss
This removes characters from the `String` - not lines.
Koraktor
sorry, had pasto error in first answer
DigitalRoss
Damn. This is even better than my attempt. ;)Use `s.to_a[i..-1].join` to get the resulting `String` again.
Koraktor
heh, I've often been frustrated in code-golf by `.to_a` doing the line break thing instead of chars like I want. FINALLY, I get a chance to use it! :-)
DigitalRoss
A nifty solution :P
khelll
Note: This will not work in Ruby 1.9, in which you'd need to do s.lines.to_a. See http://blog.grayproductions.net/articles/getting_code_ready_for_ruby_19 for more.
Greg Campbell
+1  A: 

This problem will remove the first two lines using regular expression.

Text = "One\nTwo\nThree\nFour"
Text = Text.gsub /^(?:[^\n]*\n){2}/, ''
# -----------------------------------^^  (2) Replace with nothing
# ----------------^^^^^^^^^^^^^^^^       (1) Detect first 2 lines
puts Text

EDIT: I've just saw that the question is also about 'n' lines not just two lines.

So here is my new answer.

Lines_Removed = 2
Original_Text = "One\nTwo\nThree\nFour"
Result___Text = (Original_Text.gsub(Regexp.new("([^\n]*\n){%s}" % Lines_Removed), ''))
#                                               ^^^^^^^^^^^^^^                    ^^
# - (1) Detect first  lines -----++++++++++++++                    ||
# - (2) Replace with nothing -----------------------------------------------------++

puts Result___Text # Returns "Three\nFour"
NawaMan
-1 for using constants for everything
Matt Briggs
A: 
def remove_lines(str, n)
  res = ""
  arr = str.split("\n")[n..(str.size-n)]
  arr.each { |i| res.concat(i + "\n")  }
  return res
end

a = "1\n2\n3\n4\n"
b = remove_lines(a, 2)
print b
Overdose