简体   繁体   English

Ruby On Rails ljust(5,'。')不起作用

[英]Ruby On Rails ljust(5,'.') does not work

I'm trying to left justify a string in a rails view with a pad character. 我试图在带有填充字符的rails视图中对齐字符串。

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? 如何使第一个代码段起作用?

The following works because .length gives you a number, probably zero, and then adds .... 以下工作是因为.length给您一个数字,可能为零,然后加....

<%= 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. 看起来menu_items是一个数组。 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. 另外,如果它不是数组,则将附加..以使其总长度为5。如果描述较长,则将不执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM