在视图中以电话号码格式输出整数



我试图将其显示为一个格式化的电话号码,如:xxx-xxx-xxxx,而不是当前的数字字符串。。任何帮助都会很棒!

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

您可以使用number_to_phone助手,如下所示:

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

默认情况下,它将电话号码格式化为xxx-xxxx-xxxx:

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

使用phone宝石。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"

最新更新