0

I'm trying to left justify a string in a rails view with a pad character.

The following doesn't work:

<%= menu_items.description.ljust(5,".")%>

Neither does this:

<%= menu_items.description.to_s.ljust(5,".")%>

Just to mess around and try to get something I found the following works.

<%= menu_items.description.length.to_s.ljust(5,".")%>

It prints out the length converted to a string and appends the pad characters. What gives? How do I make the first snippet work?

4

1 回答 1

1

The following works because .length gives you a number, probably zero, and then adds ....

<%= menu_items.description.length.to_s.ljust(5,".")%>

What do you get when you just do this:

<%= menu_items.description %>

Look like menu_items is an array. Try this

<% menu_items.each do |menu_item| %>
  <%= menu_item.description.ljust(5,".") %>
<% end %>

Also, if it is not an array, then the .. will be appended to make it a total length of 5. If description is longer, it will do nothing.

于 2012-06-03T05:02:57.973 回答