【问题标题】:How does one create an object from a class within a gem?如何从 gem 中的类创建对象?
【发布时间】:2015-09-16 02:00:57
【问题描述】:

假设您编写了一个包含模块中的类的 gem。如果安装该 gem 并希望从该类创建一个对象实例,他们如何在另一个 rb 文档中成功地做到这一点?这是我的宝石课程。

需要“Sentencemate/版本”

module Sentencemate
  #Object used to emulate a single word in text.
  class Word
    def initialize(word)
      @word = word
    end
    def append(str)
      @word = @word << str
      return @word
    end
    def get
      return @word
    end
    def setword(str)
      @word = str
    end
    def tag(str)
      @tag = str
    end
  end
# Object used to emulate a sentence in text.
  class Sentence
    def initialize(statement)
      @sentence = statement
      statement = statement.chop
      statement = statement.downcase
      lst = statement.split(" ")
      @words = []
      for elem in lst
        @words << Word.new(elem)
      end
      if @sentence[@sentence.length-1] == "?"
        @question = true
      else
        @question = false
      end
    end
    def addword(str)
      @words << Word.new(str)
    end
    def addword_to_place(str, i)
      @words.insert(i, Word.new(str))
    end
    def set_word(i, other)
      @words[i].setword(other)
    end
    def [](i)
      @words[i].get()
    end
    def length
      @words.length
    end
    def addpunc(symbol)
      @words[self.length-1].setword(@words[self.length-1].get << symbol)
    end
    def checkforword(str)
      for elem in @words
        if elem.get == str
          return true
        end
      end
      return false
    end
  end
end 

在 Rubymine 中,我将在 Irb 控制台中尝试以下操作:

/usr/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /usr/bin/irb --prompt simple
Switch to inspect mode.
>> require 'Sentencemate'
=> true
>> varfortesting = Sentence.new("The moon is red.")
NameError: uninitialized constant Sentence
    from (irb):2
    from /usr/bin/irb:12:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

能够使用我安装的 gem 中的类的正确方法是什么?

【问题讨论】:

  • Modulename::Classname.new 被使用

标签: ruby rubygems rubymine


【解决方案1】:

在你的Sentence 班级中

@words << Word.new(elem)

Word 被正确解析,因为 ruby​​ 首先在当前命名空间中查找(即 Sentencemate 模块)。

在该模块之外,必须使用完全限定名称,例如Sentencemate::Word。这是将这个Word 与用户的应用程序可能拥有的其他十几个Word 类区分开来的必要条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多