2014-12-05 66 views
0

因此,我是ruby的新手,正在玩一個簡單的抓取腳本。我寫道:無法從另一個類方法調用正則表達式方法

class Scrape 

    def get_attribute(html, doc) 
     doc.css(html).to_s.strip.remove_html_tags 
    end 

    public 

    def remove_html_tags 
     re = /<("[^"]*"|'[^']*'|[^'">])*>/ 
     self.gsub!(re, '') 
    end 

end 

有被排除的方法,但我跟着我的錯誤回到這個方法,我不斷收到以下每當get_attribute方法被稱爲:

NoMethodError: undefined method `remove_html_tags' for #<String:0x007fcf42fd5610> 

唯一可行的事當我直接使用弦上GSUB:

def get_attribute(html, doc) 
    doc.css(html).to_s.strip.gsub(/<("[^"]*"|'[^']*'|[^'">])*>/, '') 
end 

我試過包括本remove_html_tags方法的模塊,以及,但似乎並沒有幫助。我找不到我失蹤的東西,任何幫助將不勝感激!

回答

1

doc.css(html).to_s.strip正在爲您提供String實例,因此您需要在類String中定義方法remove_html_tags。目前,它是Scarpe類的實例方法,但您在String的實例上調用它。

你可以如下設計你的方法: -

class Scrape 
    def get_attribute(html, doc) 
     string = remove_html_tags doc.css(html).to_s.strip 
    end 

    private 

    def remove_html_tags(string) 
     re = /<("[^"]*"|'[^']*'|[^'">])*>/ 
     string.gsub(re, '') 
    end 
end 

注:如果你不想暴露remove_html_tags到外面API,你應該讓作爲private方法,否則,使它public。在公開的情況下,不需要使用關鍵字public,默認情況下所有方法的可見性都落入public

2

無論你想利用類中定義的方法Scrape你應該aknowledge紅寶石約:

#    string call string’s method 
doc.css(html).to_s.strip.remove_html_tags 

應該有所改變:

# scrape call scrape’s method 
self.remove_html_tags(doc.css(html).to_s.strip) 

remove_html_tags本身應該對字符串實例進行操作:

#     parameter 
def remove_html_tags input 
    re = /<("[^"]*"|'[^']*'|[^'">])*>/ 
    # gsubbing parameter 
    input.gsub(re, '') # using gsub not gsub! to _return_ correct result 
end 
+0

不需要「自己」... :-) – 2014-12-05 06:12:33

+0

我試圖解釋的事情,而不是混淆代碼,以最小計數的字母使用。 – mudasobwa 2014-12-05 06:13:54

+0

沒關係!:-) – 2014-12-05 06:15:16