Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 576
pakeha Avatar asked Oct 10 '09 11:10

pakeha


People also ask

What does \n do in Ruby?

In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .

What is GSUB in Ruby on Rails?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

What does GSUB return?

gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function.


1 Answers

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")
like image 182
Vincent Robert Avatar answered Oct 05 '22 18:10

Vincent Robert