在视图中将整数输出为 phone 数字格式

Output integer as phone number format in view

我正在尝试将其显示为格式化的 phone 数字,例如:xxx-xxx-xxxx 而不是像目前这样的数字字符串..任何帮助都会很棒!

<% if @post.phone.present? %>
    <h4>Phone: <small> <%= @post.phone %><br></h4>
<% end %> 

使用phonegem。 https://github.com/carr/phone

pn = Phoner::Phone.parse('+385915125486')
pn.to_s # => "+385915125486"
pn.format("%A/%f-%l") # => "091/512-5486"
pn.format("+ %c (%a) %n") # => "+ 385 (91) 5125486"
pn.format(:europe) # => "+385 (0) 91 512 5486"
pn.format(:us) # => "(234) 123-4567"
pn.format(:default_with_extension) # => "+3851234567x143"

你可以使用 number_to_phone 助手,像这样:

<% if @post.phone.present? %>
   <h4>Phone: <small> <%= number_to_phone @post.phone %><br></h4>
<% end %> 

默认情况下,它会将 phone 数字格式化为 xxx-xxx-xxxx :

2.1.1 :009 > number_to_phone(1235551234)  
 => "123-555-1234" 
2.1.1 :010 > number_to_phone("1235551234")  
 => "123-555-1234"