2011-04-25 60 views
1

使用Rails在格式化,我能格式化一個數字,美國電話號碼的使用使用歐洲手機格式number_to_phone歐洲手機滑軌

我',這意味着我要組號碼,格式如下,n是一個變量:

(n*x) xxx-xxx 

一些例子

6365555796 => (6365) 555-796 

665555796 => (665) 555-796 

如何實現與最新的軌道3.0.7?

+1

您可以舉幾個例子來加深理解嗎?特別是對於本節(n * x) – intellidiot 2011-04-25 06:45:07

回答

3

怎麼樣所以:

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" 

...

2

我認爲你必須爲此編寫自己的方法,因爲我沒有內置的方法,我認爲你可以通過編寫合適的正則表達式來實現期望的目標。

你試過validate_format_for有:有ü可以寫具體regualr表達它[見本段] http://ruby-forum.com/topic/180192編寫自己的助手吧

檢查這裏這顆寶石是你所需要的http://github.com/floere/phony

+0

afridi,爲什麼不將這些註釋轉移到您的答案中,以使其更加完整和可讀? – oma 2011-04-25 08:56:17

0

更快的方法:

def to_european_phone_format(number) 
    "(#{number/10**6}) #{number/10**3%10**3}-#{number%10**3}" 
end 
+0

不錯;)這裏不是「%10 ** 6」多餘? – 2011-04-25 10:40:39

+0

是的,是的。糾正。謝謝 :) – intellidiot 2011-04-25 11:43:03