无法从另一个类方法调用正则表达式方法

时间:2014-12-05 06:05:32

标签: ruby

所以,我是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方法,但这似乎没有帮助。我无法弄清楚我错过了什么,任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:2)

您是否想要使用类Scrape中定义的方法,您应该知道关于:

#               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

答案 1 :(得分:1)

doc.css(html).to_s.strip正在为您提供String个实例,因此您需要在类remove_html_tags中定义方法String。目前它是类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方法,否则,将其设为{{} 1}}。如果是公开的,不需要使用public关键字,默认情况下,所有方法的可见性都属于public