asf asf - 5 months ago 10
Ruby Question

Ruby - `block in initialize': undefined method

I got an error


block in initialize: undefined method `SIGN' for Mineral:Class (NoMethodError)


How can I fix it?

require "./mineral"

.
.
.
@map[x][y] = Mineral.SIGN


My class:

class Mineral
attr_accessor :x, :y, :cost, :SIGN
@@SIGN = "s"
def initialize(x, y)
@x,@y = x,y
@cost = rand 10
end
end

Answer

You need to define a getter method to access the class variables in class Mineral. The attr_accessor method does automatically define the getter and setter method for x, y, cost instance variables but there is no such facility for class variable.

Besides, if @@SIGN is not a constant (expected to change at run-time), then I suggest that you use @@sign instead of @@SIGN. Because, all capital named variables are constants in ruby - will raise error if attempted to change at run-time.

class Mineral
attr_accessor :x, :y, :cost
@@sign = "s"
def initialize(x, y)
    @x,@y = x,y
    @cost = rand 10
end

def self.get_sign
    @@sign
end
end

Further, you can access the @@sign as:

require "./mineral"

    .
    .
    .
    @map[x][y] = Mineral.get_sign

From your question it feels that you will benefit by clearing concepts of class and instance variables and methods in ruby. A good starting point is this.

Comment if you still have doubt or confusion, will be glad to clear it.

Hope it helps : )