2014-12-05 4 views
0

그래서 저는 루비를 처음 사용하고 간단한 스크랩 스크립트로 놀고 있습니다.다른 클래스 메서드에서 정규식 메서드를 호출 할 수 없습니다.

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> 

있는 유일한 방법을 나는이뿐만 아니라 모듈의 방법을 remove_html_tags 포함 시도했지만 한

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

그 도움을 보이지 않았다 : 나는 문자열에 직접 GSUB를 사용할 때입니다. 제가 누락 된 부분을 파악할 수 없기 때문에 어떤 도움을 주시면 감사하겠습니다!

답변

1

doc.css(html).to_s.stripString 인스턴스를 제공하므로 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 

참고 : 외부 API에 remove_html_tags을 노출하지 않으려는 경우, 당신은 private 방법으로 그것을해야한다, 그렇지 않으면 그것을 만들 public. 일반인의 경우 public 키워드를 사용할 필요가 없습니다. 기본적으로 모든 메소드 가시성은 public입니다.

2

당신은 당신이에 대한 루비 aknowledge한다 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 
+0

'self'가 필요하지 않습니다. :-) –

+0

나는 최소한의 문자 사용으로 코드를 모호하게하지 않기 위해, 일을 설명하려고 노력하고 있습니다. – mudasobwa

+0

괜찮습니다! .. :-) –

관련 문제