styling
styling

Reputation: 29

undefined method because of self.new?

 class Per
    def prkey(somevar)
      @card = somevar
    end

    def self.some_class
      puts self
    end

    def self.new
     @card = 'ss'
    end
   end

Per.some_class
Per.new.prkey('hi')

I got the error :

undefined method `prkey' for "ss":String (NoMethodError)

because of the self.new ? After I comment out self.new, there is no error. That is weird.

Upvotes: 0

Views: 770

Answers (3)

Kandy
Kandy

Reputation: 292

If you want to keep doing self.new implementation, you can call super to return the object you need like this:

class Per
    def prkey(somevar)
        @card = somevar
    end

    def self.some_class
        puts self
    end

    def self.new
        @card = 'ss'
        super
    end
end

Per.some_class
Per.new.prkey('hi')

However like people have already answered, it is better to implement the initialize method:

class Per
    attr_accessor :card # getter and setter for card    

    def initialize(card)
        @card = card
    end
end

per = Per.new("hi")
puts per.card # hi
per.card = "hello"
puts per.card # hello 

Upvotes: 1

eyevan
eyevan

Reputation: 1473

You overrode the new method. So now when you call Per.new, it will return ss string, rather than an instance of class Per.

Then you are calling prkey method on an instance of String class, which is not defined.

As it was recommended in the comment to your question, you need to use def initialize instead of def self.new.

Upvotes: 2

Yechiel K
Yechiel K

Reputation: 538

.new is Ruby's built in function for initializing new instances of a class, by defining your own .new you are hijacking the behaviour and therefore new instances aren't being instantiated.

If you want something to happen every time an instance of a class is instantiated put it in the initialize method.

Replace your self.new method with:

def initialize
    @card = "ss"
end

Upvotes: 4

Related Questions