English 中文(简体)
Ruby 访问其他对象的实例变量
原标题:Ruby accessing instance variable of other object
  • 时间:2012-05-27 19:36:44
  •  标签:
  • ruby

我和鲁比(Ruby 1.9.3, IRB 0.9.6(09/06/30))和我想开发一个复杂的数字类。我有了 初始化 to_s 的方法。 我现在试图让四个算术操作员超载。

我曾经有过的是:

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

但出于某种原因,它不喜欢 other. @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

虽然这样有效, 但我有一种感觉, 它不是正确的方式。 我真的不想曝光 < code> get_ values 方法; 难道没有办法我可以访问同一类中另一个实例的变量吗?

最佳回答

当提及其它实例时, 访问实例变量时不使用 :

other.real

(假设您使用 < code>attr_ accessor 来定义它们,或者提供自己的存取器。即使在同一情况下,您也可以选择使用存取器,以防逻辑超出仅返回实例变量的范围。 )

问题回答

最佳方式(在我看来)是提供只读取变量 real imag ,并使用 atr_reader 读取。 例如 :

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

注意 attr_ reader 定义您代表 . real () .imag () [ atr_accessor 的方法, 并定义了 .real= () .image= () ]





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签