Reputation: 7414
With rails, I can format a number into a US phone number with number_to_phone
I'am using using european phone format, which means that I want to group numbers with the following format, n
is a variable:
(n*x) xxx-xxx
Some examples
6365555796 => (6365) 555-796
665555796 => (665) 555-796
How to achieve that with the latest rails 3.0.7?
Upvotes: 1
Views: 281
Reputation: 5880
how about so:
def to_phone(num)
groups = num.to_s.scan(/(.*)(\d{3})(\d{3})/).flatten
"(#{groups.shift}) #{groups.shift}-#{groups.shift}"
end
irb(main):053:0> to_phone 318273612
=> "(318) 273-612"
irb(main):054:0> to_phone 3182736122
=> "(3182) 736-122"
irb(main):055:0> to_phone 31827361221
=> "(31827) 361-221"
...
Upvotes: 3
Reputation: 11228
A faster approach:
def to_european_phone_format(number)
"(#{number/10**6}) #{number/10**3%10**3}-#{number%10**3}"
end
Upvotes: 0
Reputation: 432
i think you have to write your own method for this there is no built-in method in my knowledge for it and i think you can achieved the desired thing by writing apropriate regular expression for that.
have you tried validate_format_for with: there u can write specific regualr expression for it [see this] http://ruby-forum.com/topic/180192 for writing your own helper for it
check this gem here is what you need http://github.com/floere/phony
Upvotes: 2