Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.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访问其他对象的实例变量_Ruby - Fatal编程技术网

Ruby访问其他对象的实例变量

Ruby访问其他对象的实例变量,ruby,Ruby,我一直在玩弄Ruby(Ruby 1.9.3,IRB 0.9.6(09/06/30)),我正在尝试开发一个复数类。我的initialize和to_s方法工作正常。我现在尝试重载四个算术运算符 我所拥有的是: def +(other) return ComplexNumber.new(@real + other.@real, @imag + other.@imag) end 但出于某种原因,它不喜欢其他。@real;上面说 语法错误:意外的tIVAR 并指向other.@real后面的逗号

我一直在玩弄Ruby(Ruby 1.9.3,IRB 0.9.6(09/06/30)),我正在尝试开发一个复数类。我的
initialize
to_s
方法工作正常。我现在尝试重载四个算术运算符

我所拥有的是:

def +(other)
    return ComplexNumber.new(@real + other.@real, @imag + other.@imag)
end
但出于某种原因,它不喜欢其他。@real;上面说

语法错误:意外的tIVAR

并指向
other.@real
后面的逗号

然后我把它改成:

def get_values
    return [@real, @imag]
end

def +(other)
    other_values = other.get_values
    return ComplexNumber.new(@real + other_values[0], @imag + other_values[1])
end

虽然这样做有效,但我觉得这不是正确的方法。我真的不想公开
get\u value
方法;是否有某种方法可以访问同一类的另一个实例的变量?

引用另一个实例时,在不使用
@
的情况下访问实例变量:

other.real

(假设您正在使用
attr_accessor
来定义它们,或者正在提供您自己的访问器。即使在同一个实例中,您也可能更喜欢使用访问器,以防除了返回实例变量之外还有其他逻辑。)

引用另一个实例时,访问实例变量时不使用
@

other.real
(假设您正在使用
attr\u accessor
来定义它们,或者正在提供您自己的访问器。即使在同一个实例中,您也可能更喜欢使用访问器,以防除了返回实例变量之外还有逻辑。)

最佳方法(在我看来)将使用
attr\u reader
提供对变量
real
imag
的只读访问。比如:

class ComplexNumber
  attr_reader :imag, :real
  ...
  def +(other)
    return ComplexNumber.new(@real + other.real, @imag + other.imag)
  end
end
请注意,attr\u reader代表您定义了方法
.real()
.imag()
[
attr\u访问器
另外定义了
.real=()
.image=()
]

最佳方法(在我看来)将使用
attr\u reader
提供对变量
real
imag
的只读访问。比如:

class ComplexNumber
  attr_reader :imag, :real
  ...
  def +(other)
    return ComplexNumber.new(@real + other.real, @imag + other.imag)
  end
end

请注意,attr\u reader代表您定义了方法
.real()
.imag()
[
attr\u访问器
另外定义了
.real=()
.image=()
]

当我使用
other.real
时,它假设
real
是一个方法,并抛出了一个错误。什么是
attr\u accessor
?@WChargin我不知道为什么要创建一个复杂的类,而不为不同的部分提供访问器;几乎任何带有复数的东西都需要它们。当我使用
other.real
时,它假设
real
是一个方法,并抛出了一个错误。什么是
attr\u accessor
?@WChargin我不知道为什么要创建一个复杂的类,而不为不同的部分提供访问器;几乎任何有复数的东西都需要它们。所以这四个方法都是私有的,我想?@WChargin为什么你会这么想?因为有一些set方法,它们似乎是侵入性的。只是set方法是私有的,get方法是公共的吗?@WChargin No;它们都是公开的。您也可以在文档中查找这些方法(
attr\u accessor
attr\u reader
,等等)。因此,我假设这四个方法是私有的?@WChargin您为什么会这样认为?因为有设置的方法,它们似乎具有侵入性。只是set方法是私有的,get方法是公共的吗?@WChargin No;它们都是公开的。你也可以在文档中查找这些方法(
attr_accessor
attr_reader
,等等)。Ruby有一个开箱即用的复杂类:
放入“0.3-0.5i”。to_c.class#=>Complex
Ruby有一个开箱即用的复杂类:
放入“0.3-0.5i”。to#c.class#=>Complex