JavascriptLoser
JavascriptLoser

Reputation: 1962

Undefined method, but I have clearly defined it?

I am a total beginner to Ruby and I'm trying to write a library which generates fake data. I'm getting a NoMethodError from one of my classes, but I have defined it, and I am not sure what is causing it.

Here are my classes:

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

You can see I've clearly defined the to_string() method in the Person class, but when I run my code, I get the following error:

/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>'

Upvotes: 2

Views: 1359

Answers (2)

Rohan
Rohan

Reputation: 2727

As per the source code shared, you have defined to_string as a class method and then you are trying to access it with an instance of that class.

To use it as a class method, define

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

Person.to_string()

To use it as a instance method, define

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

Person.new.to_string()

Upvotes: 2

ggorlen
ggorlen

Reputation: 56865

You can remove the self. from your method names if you want instance methods. Check Understanding self in Ruby for more details.

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

Also note that Ruby usually uses .to_s as the default to string method.

Upvotes: 0

Related Questions