[英]Using gsub to replace a particular character with a newline (Ruby, Rails console)
Annoying problem. 烦人的问题。 I am trying to replace all semicolon characters in my Model's description field with newline characters (\\n).
我试图用换行符(\\ n)替换模型描述字段中的所有分号字符。 The database is sqlite.
该数据库是sqlite。 The field is of type text.
该字段是文本类型。
If I do it manually at the rails console (manually typing the description for a single record using \\n for line breaks), the rails console automatically escapes the \\n, and the description field becomes filled with \\\\n
. 如果我在rails控制台上手动执行此操作(使用\\ n手动输入单个记录的描述来换行),rails控制台会自动转义\\ n,并且描述字段将变为
\\\\n
。
If I do it programmatically using gsub, I get the following situation: 如果使用gsub以编程方式进行操作,则会出现以下情况:
>> s = Sample.find(:first)
=> ...details of record ... => ...详细记录...
>> s.description.gsub!(/;/,"\n")
=> ...success - it all looks good, new lines in the returned value are represented by \\n... => ...成功-一切看起来不错,返回值中的新行用\\ n表示。
>> s.save
=> true
>> reload!
Reloading
=> true
>> s = Sample.find(:first)
=> ...details of record ... => ...详细记录...
>> s.description
=> ... the description field still has semicolons in it rather than newline characters ... => ... description字段中仍带有分号而不是换行符...
AHHHHHH!!!!!!! AHHHHHH !!!!!!!
s.description
returns a copy of the description so gsub!
s.description
返回描述的副本,所以gsub!
will only modify the copy and return the modified copy. 只会修改副本并返回修改后的副本。
Try this: 尝试这个:
s.description = s.description.gsub(/;/,"\n")
如果您要大量编辑ActiveRecord字段,则可以使用rails插件console_update在编辑器中对其进行编辑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.