2

I have a string:

str="Myname"

I want to add four white spaces after the string. What I did was:

str=str+"    "+"somename"

When I print the str as <%= str %>, the output shows only one white space. How can I make this work? I also tried:

str=str+" "*4+"somename"  

This also gives the same output as the one above gives. I don't want to print this. The string is used as a Ruby variable for more other operations. I can make it in Ruby, but not in RoR.

sawa
  • 165,429
  • 45
  • 277
  • 381
ѕтƒ
  • 3,547
  • 10
  • 47
  • 78

6 Answers6

5

This has to do with how HTML handles whitespace. Which I assume you are using based on the Erb like syntax you used. If you really must output whitespace use &nbsp;.

But I suggest you try to fix this with CSS.

harm
  • 10,045
  • 10
  • 36
  • 41
  • no. i want it in ruby. this is not for printing. this string is using to search in database – ѕтƒ Feb 28 '13 at 11:15
  • Could you edit the question to show exactly where you are using it? To me the `<%= %>` seems rather odd. – harm Feb 28 '13 at 11:26
  • Perhaps it is [sprintf](http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-sprintf) what you are looking for. – harm Feb 28 '13 at 11:27
2

Following your same structure, it would be

str = raw(str + "&nbsp;&nbsp;&nbsp;&nbsp;" + "somename")

In HTML, only a single white space in counted, regardless of how many. So you must use the HTML Entity &nbsp; (means Non Breaking SPace) to show more than one space.

The raw part is required because Rails, by default, does not allow HTML Entities or any actual HTML to be output by strings, because they can be used by nefarious users to attack your site and/or users.

Therefore, you must use raw and also use &nbsp; in Rails.

aaron-coding
  • 2,571
  • 1
  • 23
  • 31
0

There may be 4 spaces in your variable but browser truncate the extra spaces after 1 space so you may not be viewing them. try following

<pre>
<%= str %>
</pre>

You will see spaces are added to your code. To achieve what you are trying to do put   rather then blank space

Ankit
  • 1,867
  • 2
  • 21
  • 40
0

if you try following code in console you will see that the issue is with your html;

str="Myname"
str=str+"    "+"somename"

=> "Myname    somename"

try it as follow

<pre>
  <%= str %>
</pre>
Muhamamd Awais
  • 2,385
  • 14
  • 25
0

you can replace the spaces with html encoding string and then render with html_safe or raw like,

<%= raw "Myname    somename".gsub(/\s/, "&nbsp;") %>
maximus ツ
  • 7,949
  • 3
  • 25
  • 54
0
<pre>I am a bad web programmer</pre>

pre tags of the bane of existence and should be avoided at all costs. Use this in your erb.

<%= raw(CGI.escapeHTML(str).gsub(/\s/, '&nbsp;')) %>
Jeremiah
  • 61
  • 1
  • 2