Rails beginner
Rails beginner

Reputation: 14514

Ruby string manipulation how to add space?

I am having problems string manipulation.

Here is to achieve with my string manipulation:

What I have:

<item name="RFSF "Blindspot"" type="project" id="34"/>

I want to add a line break just before the "" and it should also gsub all existing white space.

Here is the XML generator:

xmlmenu.item(:name=> convert_html_entities(kidsmovies[n].name),  :type=>"project", :id=> kidsmovies[n].id)      

Example want I want to do:

xmlmenu.item(:name=> convert_html_entities(kidsmovies[n].name).gsub(remove all whitespace).gsub(add one whitespace between the words).gsub.(create a linebreak just before ""),  :type=>"project", :id=> kidsmovies[n].id)  

Upvotes: 0

Views: 733

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37527

Put this in a helper:

def format_name(str)
  html_escape(str.gsub(/\s+/, " ")) + "\n"
end

Then use it instead of convert_html_entities, which is not working (because it is not escaping quotes, making the XML output invalid). LIke so:

xmlmenu.item(:name=> format_name(kidsmovies[n].name), :type=>"project", :id=> kidsmovies[n].id)

Upvotes: 1

Oleksandr Skrypnyk
Oleksandr Skrypnyk

Reputation: 2830

First of all, you have a bad XML, it must be:

<item name="RFSF \"Blindspot\"" type="project" id="34"/>

then, to cut out extra spaces:

string.gsub(/\S+/).map.join(' ')

or:

string.split(' ').join(' ')

But what is create a linebreak just before ""?

Upvotes: 1

Related Questions