让我们假设您在模块中编写包含类的gem。如果安装了那个gem并希望从该类创建一个对象实例,那么他们如何在另一个rb文档中成功完成呢?这是我的宝石课。
要求“Sentencemate / version”
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中使用类的正确方法是什么?
答案 0 :(得分:1)
在Sentence
班级
@words << Word.new(elem)
Word
已正确解析,因为ruby首先在当前命名空间中查找(即Sentencemate
模块)。
在该模块之外,必须使用完全限定名称,例如Sentencemate::Word
。这有必要将此Word
与用户应用可能拥有的其他Word
个类区分开来。