使用 gsub 用换行符替换特定字符(Ruby、Rails 控制台)
烦人的问题。我试图用换行符 (\n) 替换模型描述字段中的所有分号字符。数据库是sqlite。该字段的类型为文本。
如果我在 Rails 控制台手动执行此操作(使用 \n 进行换行手动输入单个记录的描述),rails 控制台会自动转义 \n,并且描述字段将填充为 \\n.
如果我使用 gsub 以编程方式执行此操作,则会出现以下情况:
>> s = Sample.find(:first)
=> ...记录详情...
>> s.description.gsub!(/;/,"\n")
=> 表示
>> s.save
=> true
>> reload!
Reloading
=> true
>> s = Sample.find(:first)
...成功 - 一切看起来都不错,返回值中的新行由 \n... => ...记录详情...
>> s.description
=> ...描述字段中仍然有分号而不是换行符...
AHHHHHH!!!!!!!
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.
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
.
If I do it programmatically using gsub, I get the following situation:
>> 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...
>> 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!!!!!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
s.description
返回描述的副本,因此gsub!
只会修改该副本并返回修改后的副本。试试这个:
s.description
returns a copy of the description sogsub!
will only modify the copy and return the modified copy.Try this:
如果您经常编辑 ActiveRecord 字段,则可以使用 Rails 插件 console_update< 在编辑器中编辑它们/a>
If you're editing ActiveRecord fields a lot, you can just edit them in your editor with the rails plugin console_update