Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby-`block in initialize';:未定义方法_Ruby - Fatal编程技术网

Ruby-`block in initialize';:未定义方法

Ruby-`block in initialize';:未定义方法,ruby,Ruby,我犯了个错误 初始化中的块:矿物类的未定义方法“符号”(NoMethodError) 我怎样才能修好它 require "./mineral" . . . @map[x][y] = Mineral.SIGN 我的班级: class Mineral attr_accessor :x, :y, :cost, :SIGN @@SIGN = "s" def initialize(x, y) @x,@y = x,y @cost = rand

我犯了个错误

初始化中的块:矿物类的未定义方法“符号”(NoMethodError)

我怎样才能修好它

 require "./mineral"

    .
    .
    .
    @map[x][y] = Mineral.SIGN
我的班级:

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

您需要定义一个
getter
方法来访问类中的类变量。
attr\u accessor
方法会自动为
x
y
cost
实例变量定义getter和setter方法,但对于类变量没有此类工具

此外,如果
@@SIGN
不是常量(预计在运行时会更改),则我建议您使用
@@SIGN
而不是
@@SIGN
。因为,所有大写变量在ruby中都是常量-如果试图在运行时更改,将引发错误

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
此外,您还可以通过以下方式访问
@@sign

require "./mineral"

    .
    .
    .
    @map[x][y] = Mineral.get_sign
从您的问题中,您会感觉到,在ruby中清除类和实例变量以及方法的概念将使您受益匪浅。一个好的起点是

如果您仍有疑问或困惑,请发表评论,我们很乐意澄清


希望对您有所帮助:)

在程序运行期间是否会更改
@@SIGN

如果它会改变:您可能希望遵循Ruby约定,并为此类类层次结构变量使用小写名称。此外,您还需要一个getter方法(可能还有setter):

如果不更改,请使用常量而不是类层次结构变量:

# in your model
SIGN = 's'

# usage
@map[x][y] = Mineral::SIGN

@@SIGN
常量”-
@@SIGN
在这里绝对不是常量。@mudasobwa如果
@@SIGN
不是常量,他就不应该用大写字母命名该变量。因为在ruby中,所有大写的变量都被视为常量。因此,我建议他在这种情况下使用
@@sign
而不是
@@sign
。可能会也可能不会遵循ruby约定
SIGN
隐式声明为常量,而
@SIGN
实例变量和
@@SIGN
类变量,甚至方法
def SIGN
都不是常量。更重要的是:Ruby core中有许多方法,主要是在
内核上定义的,它们以大写字母命名:
Integer()
Array()
等等。
# in your model
SIGN = 's'

# usage
@map[x][y] = Mineral::SIGN