p "line\n".chomp #=> "line" p "line\r\n".chomp #=> "line" p "line\r".chomp #=> "line" p "line \t\n".chomp #=> "line \t" p "line".chomp #=> "line" |
但是, 有时只想删除 \r\n 并不想删除 独立的 \r 或 \n 时,可以对 String#chomp的 删除模式进行设置
$\ = "\r\n" p "line\n".chomp #=> "line\n" p "line\r\n".chomp #=> "line" p "line\r".chomp #=> "line\r" p "line \t\n".chomp #=> "line \t\n" p "line".chomp #=> "line" |
还可以为 String#chomp 添加参数, 来实现将在已经设定模式内的某一字符删除
$\ = "\r\n" p "line\n".chomp("\n") #=> "line" p "line\r\n".chomp("\n") #=> "line" p "line\r".chomp("\n") #=> "line" p "line \t\n".chomp("\n") #=> "line \t" p "line".chomp("\n") #=> "line" |
在对一些文本文件进行处理时, 行末不仅有回车,还会有空格等字符。如果想一并删 除时, 使用 String#rstrip
p "line\n".rstrip #=> "line" p "line\r\n".rstrip #=> "line" p "line\r".rstrip #=> "line" p "line\t \n".rstrip #=> "line" p "line".rstrip #=> "line" |
没有评论:
发表评论