使用 gsub 用换行符替换特定字符(Ruby、Rails 控制台)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1547668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:50:43  来源:igfitidea点击:

Using gsub to replace a particular character with a newline (Ruby, Rails console)

ruby-on-railsrubystringnewlinegsub

提问by pakeha

Annoying problem. I am trying to replace all semicolon characters in my Model's description field with newline characters (\n). The database is sqlite. The field is of type text.

烦人的问题。我试图用换行符 (\n) 替换模型描述字段中的所有分号字符。数据库是sqlite。该字段是文本类型。

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 ...

=> ...描述字段中仍然有分号而不是换行符...

AHHHHHH!!!!!!!

啊啊啊啊啊!!!!!!

回答by Vincent Robert

s.descriptionreturns a copy of the description so gsub!will only modify the copy and return the modified copy.

s.description返回描述的副本,因此gsub!只会修改副本并返回修改后的副本。

Try this:

尝试这个:

s.description = s.description.gsub(/;/,"\n")

回答by cldwalker

If you're editing ActiveRecord fields a lot, you can just edit them in your editor with the rails plugin console_update

如果你经常编辑 ActiveRecord 字段,你可以在你的编辑器中使用 rails 插件console_update编辑它们