2016-08-12 55 views
1

我想從字符串中提取整數,並利用它們通過YAML文件中像這樣來掃描提取:如何從字符串中提取數字,並用它們來從YAML文件

FORMS = YAML.load_file('../email/lib/lists/form_links.yml') 

def get_form(form) 
    form_num = form.scan(/\d+/) 
    data = FORMS['esd_forms'][form_num] 
    begin 
    if data != nil 
     "Form link: #{data}" 
    else 
     raise StandardError 
    end 
    rescue StandardError 
    "** Form: #{form} is not a valid form name **" 
    end 
end 

YAML文件:

esd_forms: 
    1: 'http://labornet.com/itc/ESD-1.pdf' 
    2: 'http://labornet.com/itc/ESD-2.pdf' 
    3: 'http://labornet.com/itc/ESD-3.pdf' 
    4: 'http://labornet.com/itc/ESD-4.pdf' 
    5: 'http://labornet.com/itc/ESD-5.pdf' 
    6: 'http://labornet.com/itc/ESD-6.pdf' 
    7: 'http://labornet.com/itc/ESD-7.pdf' 
    8: 'http://labornet.com/itc/ESD-8.pdf' 
    9: 'http://labornet.com/itc/ESD-9.pdf' 
    10: 'http://labornet.com/itc/ESD-10.pdf' 
    11: 'http://labornet.com/itc/ESD-11.pdf' 
    03: 'http://labornet.com/itc/OCIO-IT-03.pdf' 
    07: 'http://labornet.com/itc/OCIO-IT-07.pdf' 
    10: 'http://labornet.com/itc/OCIO-10.pdf' 
    13: 'http://labornet.com/itc/ESD-13.pdf' 
    14: 'http://labornet.com/itc/ESD-14.pdf' 

當我這樣做,我得到一個錯誤:

wrong argument type Array (expected Regexp) 

我不明白爲什麼我得到這個錯誤。起初我還以爲是因爲該程序返回一個數組,而不是字符串,所以我想它在IRB:

irb(main):001:0> form = 'esd-2' 
=> "esd-2" 
irb(main):002:0> form_num = form.scan(/\d+/) 
=> ["2"] 
irb(main):003:0> puts form_num 
2 

對我來說,這似乎是我正確的事情了。我究竟做錯了什麼?

+0

你怎麼打電話給你'get_form'功能?該錯誤的準確位置是什麼? – mudasobwa

+1

在詢問您編寫的代碼時,我們能夠複製問題而不必編寫代碼進行測試是非常重要的,否則我們可能會意外更改問題並提供不適合或無法幫助的答案。我們可以根據您的IRB會議將其組合在一起,但迫使我們這樣做會減慢我們幫助您的能力,浪費我們,您和其他在隊列中有問題的人的時間。閱讀「[mcve]」和http://catb.org/esr/faqs/smart-questions.html,討論如何提出這些問題。 –

回答

1

String#scan返回所有出現在匹配正則表達式,在陣列中的字符串。

當你執行form_num = form.scan(/\d+/)時,你會在你的irb會話中看到,它實際上返回一個包含1個元素["2"]的數組。

如果你想返回第一個匹配的部分,你可以使用String#[]

form = 'esd-2' 
form_num = form[/\d+/] 
#=> "2" 

此外,如果你需要檢查什麼是存儲在一個變量,p會比puts一個更好的選擇。 irb實際上使用p默認輸出表達式結果,就像你在irb會話中看到的一樣。

form = 'esd-2' 
form_num = form.scan(/\d+/) 
puts form_num 
#=> 2 
p form_num 
#=> ["2"] 
+0

這很有道理,但我確實有一個問題。當我把'form_num'放在'irb'中時,它怎麼輸出'2'? –

+0

@ YoYoYoI'mAwesome如果用數組調用'puts',它將逐行輸出數組中的每個元素。 –

+0

它仍然輸出'**形式:ESD-2不是一個有效的形式,名稱**' –