Ruby 从字符串中删除空行 [英] Ruby remove empty lines from string

查看:34
本文介绍了Ruby 从字符串中删除空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从字符串中删除空行?我试过了some_string = some_string.gsub(/^$/, "");

How do i remove empty lines from a string? I have tried some_string = some_string.gsub(/^$/, "");

还有更多,但没有任何效果.

and much more, but nothing works.

推荐答案

删除空行:

str.gsub /^$\n/, ''

注意:与其他一些解决方案不同,这个解决方案实际上删除了空行而不是换行符 :)

Note: unlike some of the other solutions, this one actually removes blank lines and not line breaks :)

>> a = "a\n\nb\n"
=> "a\n\nb\n"
>> a.gsub /^$\n/, ''
=> "a\nb\n"

说明:匹配一行的开始^和结束$,中间没有任何内容,后跟一个换行符.

Explanation: matches the start ^ and end $ of a line with nothing in between, followed by a line break.

另一种更明确(虽然不太优雅)的解决方案:

Alternative, more explicit (though less elegant) solution:

str.each_line.reject{|x| x.strip == ""}.join

这篇关于Ruby 从字符串中删除空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆