2013-01-23 36 views
-3

我是新來的紅寶石。我正在嘗試解析CSV文件中的電話號碼,並使用以下代碼進行了處理。它工作正常。從解析的CSV文件清理電話號碼

require 'csv' 
csv_text = File.read('file.csv') 
csv = CSV.parse(csv_text, :headers => true) 
csv.each do |row|          
    puts "Home Phone: #{row['HomePhone']}" 
end 

我想要的是通過以下方式清理HomePhone。

  1. 如果電話號碼有10位數字,那就好,就這樣打印。
  2. 如果電話號碼少於10位,打印無效號碼爲「0000000000」
  3. 如果電話號碼有11位數字,第一個數字是1,打印最後10位數字(除去第1),否則爲「0000000000」

我不知道該怎麼做。

+0

如果它有11位和第一位不爲1,或者如果它有超過11位會發生什麼? – sawa

回答

2

你可以用恰當地命名length方法的字符串的長度:

string = 'foobar' 
string.length # => 6 

可以檢查字符串使用另一個字符串開頭:

string.start_with?('f') # => true 

您可以切分個人字符串l使用數組索引符號(方括號)和範圍的字符。負指數從字符串的末尾開始計數。因此,要返回所有,但第一個字符:

string[1..-1] # => 'oobar' 

所以做你的要求,你可以將這些

home_phone = row['HomePhone'] 
if home_phone.length == 10 
    puts home_phone 
elsif home_phone.length == 11 && home_phone.start_with?('1') 
    puts home_phone[1..-1] 
else 
    puts '0000000000' 
end 

注意,這種方法假定您的電話號碼已經是數字和你串什麼只需要檢查他們的長度。如果你想更徹底,檢查含非數字字符無效電話號碼,像123z567890,你可能會考慮一個正則表達式的方法:

if match = /^1?(?<number>\d{10})$/.match(row['HomePhone']) 
    puts match[:number] 
else 
    puts '0000000000' 
end 

,這個正則表達式匹配的組件:

  • ^ - 任選的1
  • (?<number>\d{10}) - - 串
  • 1?的開始保存的一組中的10位數字(即\d{10})稱爲number
  • $ - 字符串

紅寶石的端部使用斜線來分隔的正則表達式,以及match方法返回一個對象,我們可以使用以提取所保存的10位數字。

0

試試下面的代碼

csv.each do |row| 
    phone_number = row['HomePhone'].to_s 
    if phone_number.length == 10 
    puts "Home Phone: #{phone_number}" 
    elsif phone_number.length == 11 && phone_number[0] == "1" 
    puts "Home Phone: #{phone_number[1..10]}" 
    else 
    puts "Home Phone: 0000000000" 
    end 
end 
0

要把它放到你的每個塊:

phone_number = row['HomePhone'] 
if phone_number.length == 10 
    puts "Home Phone: #{row['HomePhone']}" 
elsif (phone_number.length == 11 and x[0] == "1") 
    phone_number.slice!(0)  # remove first character 
    puts phone_number 
else 
    puts "0000000000" 
end