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

Annoying problem. I am trying to replace all semicolons in the model description field with newline characters (\ n). The database is sqlite. The field has a text type.

If I do this manually in the rails console (manually entering a description for a single entry using \ n for line breaks), the rails console automatically escapes \ n and the description field is populated with \\n .

If I do this programmatically using gsub, I get the following situation:

 >> s = Sample.find(:first) 

=> ... record details ...

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

=> ... success - everything looks good, new lines in the returned value are presented \ n ...

 >> s.save => true >> reload! Reloading => true >> s = Sample.find(:first) 

=> ... record details ...

 >> s.description 

=> ... there are still semicolons in the description field, not newline characters ...

AHHHHHH !!!!!!!

+6
string ruby ruby-on-rails newline gsub
source share
2 answers

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

Try the following:

 s.description = s.description.gsub(/;/,"\n") 
+27
source share

If you edit ActiveRecord fields a lot, you can simply edit them in your editor using the rails console_update plugin

0
source share

All Articles