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

23,820

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

Try this:

s.description = s.description.gsub(/;/,"\n")
Share:
23,820
R. Kuroshima
Author by

R. Kuroshima

Updated on October 12, 2020

Comments

  • R. Kuroshima
    R. Kuroshima over 3 years

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

  • owl
    owl over 14 years
    He's using gsub! which will modify-in-place description and save it.
  • R. Kuroshima
    R. Kuroshima over 14 years
    That's what I thought too, Radar. However Vincent's solution seems to work. Using the destructive variant of gsub wasn't working for me. The field was unmodified after performing a save. I was working in the rails console if that makes a difference.