浏览Ruby对象

时间:2015-01-07 08:19:18

标签: ruby oop

在红宝石物体内导航非常简单。给定以下伪代码,并使用此段落作为示例输入,以下调用有意义并且有效:

forth_word = Par.sentence[0].word[3]
puts forth_word.text #"ruby"
puts forth_word.type #:noun

彼此包含的类的伪代码:(有点嵌套但不是严格的OOP意义)

class Paragraph 
  @page_number = #1 (default)
  @sentences = []
end

class Sentence
  @is_a_quote = #false (default)
  @words = []
end

class Word
  @text =# "ruby"
  @type =# :noun 

  def in_a_quote?
    #... return Sentence.@is_a_quote 
  end

  def on_page
    #... return Paragraph.Sentence.page
  end
end

当我尝试导航Ruby对象树时,棘手的部分就变成了......也就是来自Word内部属于Sentence或Paragraph对象的信息。任何建议如何编写最后两种方法:

puts forth_word.in_a_quote  #false
puts forth_word.on_page     #1

2 个答案:

答案 0 :(得分:2)

每个单词都可以有一个句子变量,指向它所在的句子。句子和段落,段落和页面相同。

答案 1 :(得分:0)

首先,你的课程没有嵌套。它们应该在彼此内部声明。

class Paragraph 
  @page_number = #1 (default)
  @sentences = []

    class Sentence
      @is_a_quote = #false (default)
      @words = []

        class Word
          @text =# "ruby"
          @type =# :noun 
        end
    end
end

但与Ruby中的Java不同,您无法从内部类访问外部类的变量。 Ruby Constants and Nested Classes 使用模块比嵌套类更好。

但是,如果您仍想使用与示例中相同的层次结构,请注意访问类外的数据。 例如,如果您尝试执行此段代码,则会收到错误

class Word
  @text =# "ruby"
  @type =# :noun 

  def in_a_quote?
    #... return Sentence.@is_a_quote 
  end
end

w = Word.new
w.is_a_quote?  

这非常危险,与OOP原则相矛盾。