tags:

views:

55

answers:

3

ok, I have the following, very simple code:

f = "String1\n\n\nString2\n\n\n"
f.each_line do |t|
  t.delete! "\n"
  puts t.inspect
end

It removes the \n, but leaves the spaces

"String1"
nil
nil
"String2"
nil
nil

I want it to look like this:

"String1"
"String2"

Thanks in advance for help.

A: 

You could split the string by \n, and then reject any blank lines:

f = "String1\n\n\nString2\n\n\n"
f.split("\n").reject { |i| i.empty? }
#=> ["String1", "String2"]

You'd end up with an Array that you can output as you'd like.

Daniel Vandersluis
Works very well. Thanks
nomoreflash
can you split the string by nil?
nomoreflash
+3  A: 
f.squeeze("\n").each_line do |l|
  puts l
end
jordinl
Excellent answer! Thanks for the help
nomoreflash
A: 
f = "String1\n\n\nString2\n\n\n"
f.each_line.collect(&:chomp).reject(&:empty?)
#=> ["String1", "String2"]

The collect(&:chomp) removes line endings. reject(&:empty?) throws away all of the empty lines.

Wayne Conrad
Thanks, will definitely have use for your input.
nomoreflash
You're very kind. @jordinl's answer is clearly better.
Wayne Conrad