未定义的方法,但是我已经明确定义了吗?

时间:2018-07-16 04:54:33

标签: ruby

我是Ruby的初学者,我正在尝试编写一个生成伪造数据的库。我从一个课程中获得了NoMethodError,但是我已经定义了它,并且不确定是什么原因造成的。

这是我的课程:

EntityFaker.rb

=begin
    EntityFaker.rb
=end

require_relative "EntityFactory"

class Main

    public
    def self.generate_entities()
        puts "Generating entities..."
        EntityFactory.test_function()
    end

    generate_entities()
end

EntityFactory.rb

=begin
    Entity-Factory
=end

require 'faker'
require_relative 'Entities/Person'

class EntityFactory

    @@person_array = []

    public
    def self.test_function()
        generate_people(10)
    end

    private
    def self.generate_people(number)
        p = Person.new(age = number)
        puts p.to_string()
        # number.times do |n|
        #     p = Person.new(age = n)
        #     puts p.to_string()
        # end
    end
end

Person.rb

=begin
    Person.rb
=end

class Person

    def initialize(age = nil)
        @@age = age
    end

    public
    def self.to_string()
        return "#{@@age}"
    end
end

您可以看到我在to_string()类中明确定义了Person方法,但是当我运行代码时,出现以下错误:

/home/user/Documents/entity-faker/EntityFactory.rb:20:in `generate_people': undefined method `to_string' for #<Person:0x0000564f481ddbc8> (NoMethodError)
    from /home/user/Documents/entity-faker/EntityFactory.rb:14:in `test_function'
    from EntityFaker.rb:12:in `generate_entities'
    from EntityFaker.rb:15:in `<class:Main>'
    from EntityFaker.rb:7:in `<main>'

2 个答案:

答案 0 :(得分:2)

根据共享的源代码,您已将to_string定义为类方法,然后尝试使用该类的实例访问它。

要将其用作类方法,请定义

def self.to_string()
    return "#{@@age}"
end

Person.to_string()

要将其用作实例方法,请定义

def to_string()
    return "#{@@age}"
end

Person.new.to_string()

答案 1 :(得分:0)

如果需要实例方法,则可以从方法名称中删除self.。检查Understanding self in Ruby了解更多详细信息。

class Person

    def initialize(age = nil)
        @@age = age
    end

    public
    def to_string()
        return "#{@@age}"
    end
end

p = Person.new(13)
puts p.to_string() // 13

还请注意,Ruby通常使用.to_s作为字符串方法的默认方法。

相关问题