Jorge Cuevas Jorge Cuevas - 1 year ago 97
HTML Question

How to format number_to_phone for another country in Rails 4?

I'm having some issues with number formatting in rails.

I tried some suggestions from the community when working with string formatting and also the documentation resources:

The thing I tried were these:

<%= number_to_phone(, {:groupings => [4,3,3], delimiter: "-"}) %>


<%= number_to_phone(, pattern: /(\d{2})(\d{5})(\d{5})$/)) %>

None of these turned out to work for me even though the documentations states:

Formats a number into a phone number (US by default e.g., (555) 123-9876). You can customize the format in the options hash.

and the example provided is:

number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/))

=> "133-1234-5678"

I want to format it like this:


What am I missing so this code works the way I expect?

Answer Source

You could always write your own helper method if you want to:

def num_to_phone(num)
  "(#{ num[0..1] })-#{ num[2..5] }-#{ num[6..-1] }"