Jorge Cuevas Jorge Cuevas - 5 months ago 21
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:

http://edgeapi.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_phone

The thing I tried were these:

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


and

<%= number_to_phone(client.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:


(12)-3456-7890


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

Answer

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] }"
end
Comments