简体   繁体   English

红宝石类未定义方法(NoMethodError)

[英]ruby class undefined method (NoMethodError)

Unfortunately, I get the following error. 不幸的是,我收到以下错误。 I can't quite understand why it doesn't work? 我不太明白为什么它不起作用?

:14:in `convert': undefined method `factors' for 30:Fixnum (NoMethodError)
    from question_stack.rb:18:in `<main>'

I try to create the following class: 我尝试创建以下类:

# Class Wordgame
class Wordgame
  WORDGAME_MAP = {
    '3' => 'baa',
    '5' => 'bar',
    '7' => 'bla'
  }.freeze

  def self.factors
    (1..self).select { |n| (self % n).zero? }
  end

  def self.convert(number)
    number.factors.map(&:to_s).each.map { |char| WORDGAME_MAP[char] }.join
  end
end

Wordgame.convert(30)

What am I doing wrong? 我究竟做错了什么? Where is my mental error? 我的精神失误在哪里?

self refers to the class itself in a class method or to the current object in an instance method. self在类方法中引用类本身,在实例方法中引用当前对象。 In your case it refers to WordGame , the object's class. 在您的情况下,它引用对象的类WordGame

If you really want it to refer to 30 into the factors method you have to define it as an instance method, because called on an object ( 30 ), not a class ( Integer ), opening the Integer class 如果您确实希望它在factors方法中引用30则必须将其定义为实例方法,因为调用了对象( 30 )而不是类( Integer ),从而打开了Integer

class Integer
  def factors
    (1..self).select { |n| (self % n).zero? }
  end
end

I think you know the alternative: 我认为您知道另一种选择:

def self.factors(x)
  (1..x).select { |n| (self % n).zero? }
end

def self.convert(number)
  factors(number).map(&:to_s).each.map { |char| WORDGAME_MAP[char] }.join
end

Or better, with OOP. 或者更好,使用OOP。

class WordGame
  def initialize(n)
    @n = n
  end

  def convert
    factors.map(&:to_s).each.map { |char| WORDGAME_MAP[char] }.join
  end

  private

  def factors
    (1..@n).select { |m| (@n % m).zero? }
  end
end

Wordgame.new(30).convert

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM