简体   繁体   English

Ruby gsub不替换换行符

[英]Ruby gsub not replacing newline character

I have this code 我有这个代码

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

the first gsub replaces an unwanted message and the second gsub it meant to replace all the newline characters with html line breaks 第一个gsub替换不需要的消息,第二个gsub替换为用html换行符替换所有换行符

at the first debugger line 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" 在调试器的第一行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"

and at the second debugger the line hasn't changed 在第二个调试器中,该行没有更改

what's even more weird is that I did this in irb at the command line and it worked 更奇怪的是,我在命令行中在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 >

You can call gsub! 您可以致电gsub! to mutate the string you are calling it on (instead of returning a new string). 更改您要调用的字符串(而不是返回新字符串)。

The reason gsub "works" in irb is because it is outputting the result - irb does not do any assignment or mutation (beyond what one enters), eg gsub在irb中“起作用”的原因是因为它正在输出结果-irb不进行任何赋值或变异(超出输入的范围),例如

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

foo is getting assigned 4 so it outputs the result of that assignment, likewise with foo + 6 it outputs the result but the value of foo is unchanged. foo被赋值为4因此它输出该赋值的结果,与foo + 6它输出结果,但foo的值不变。

When you call gsub it returns a new string with the substitution(s), this is why you feel it "works" in irb (this is no different then it printing "4" above). 当您调用gsub它返回带有替换的字符串,这就是为什么您认为它在irb中“有效”的原因(与上面打印“ 4”没有什么不同)。

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

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