문제

I have the following block of Ruby code within a class:

def self.blacklisted_keywords
  %w(acquista acquistiamo acquisto acquistano compro compriamo comprano)
end

private

def item_valid?
  keywords = blacklisted_keywords
end

Why can't I call blacklisted_keywords without getting: "undefined method `blacklisted_keywords'"? What am I doing wrong?

도움이 되었습니까?

해결책

Because blacklisted_keywords is not an instance method, rather a class method.keywords = blacklisted_keywords means ruby looking at it implicitly as keywords = self.blacklisted_keywords. That causes an error, as it is not an instance method. Replace keywords = blacklisted_keywords as keywords = self.class.blacklisted_keywords

다른 팁

Following the answers provided, maybe it would make sense to keep the keywords in a constant if you don't need to mutate them.

class Blah
  BLACKLISTED_KEYWORDS = %w(acquista acquistiamo acquisto acquistano compro compriamo comprano)

  private

  def item_valid?
    keywords = BLACKLISTED_KEYWORDS
  end
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top