deleting blank lines after loop

后端 未结 3 660
滥情空心
滥情空心 2021-01-25 19:51

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
<
相关标签:
3条回答
  • 2021-01-25 20:01
    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.

    0 讨论(0)
  • 2021-01-25 20:07

    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.

    0 讨论(0)
  • 2021-01-25 20:11
    f.squeeze("\n").each_line do |l|
      puts l
    end
    
    0 讨论(0)
提交回复
热议问题