繁体   English   中英

Ruby gsub不替换换行符

[英]Ruby gsub not replacing newline character

我有这个代码

str = @universal_claim_form.errors.full_messages.join
        str.gsub('Patient Contact Information: Value', 'Patient phone number') if str =~ /Patient Contact Information/
        debugger
        str.gsub("\\n", "<br/>")
        debugger
        flash.now[:error] = "Form has errors and was unable to be submitted.<br/> " << str

第一个gsub替换不需要的消息,第二个gsub替换为用html换行符替换所有换行符

在调试器的第一行str = "PMP Validation failed. This happens when something you entered does not pass PMP specific validations.\\\\nPatient phone number: Value must be a 10 digit number"

在第二个调试器中,该行没有更改

更奇怪的是,我在命令行中在irb中完成了此操作,

2.1.1 :001 > s = 'test'
 => "test"
2.1.1 :002 > s
 => "test"
2.1.1 :003 > s += '\ntest'
 => "test\\ntest"
2.1.1 :004 > s.gsub('\\n', '<br/>')
 => "test<br/>test"
2.1.1 :005 >

您可以致电gsub! 更改您要调用的字符串(而不是返回新字符串)。

gsub在irb中“起作用”的原因是因为它正在输出结果-irb不进行任何赋值或变异(超出输入的范围),例如

irb(main):001:0> foo = 4
=> 4
irb(main):002:0> foo + 6
=> 10

foo被赋值为4因此它输出该赋值的结果,与foo + 6它输出结果,但foo的值不变。

当您调用gsub它返回带有替换的字符串,这就是为什么您认为它在irb中“有效”的原因(与上面打印“ 4”没有什么不同)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM