我当时正在阅读Ruby的“为什么(尖刻)指南”,并偶然发现了一种方法,它的效果并不像预期的那么好。该方法的目的是返回给定字符串的值(从哈希),有点像编码器-解码器。最初,该方法是在class String中编写的,但我修改了它以更改类名。下面是代码:
class NameReplacer
@@syllables = [
{"Paij" => "Personal","Gonk" => "Business", "Blon" => "Slave", "Stro" => "Master", "Wert" => "Father", "Onnn" => "Mother"},
{"ree" => "AM", "plo" => "PM"}
]
# method to determine what a certain name of his means
def name_significance
# split string by -
parts = self.split("-")
# make duplicate of syllables
syllables = @@syllables.dup
signif = parts.collect {|name| syllables.shift[name]}
#join array returned by " " forming a string
signif.join(" ")
end
end要运行这段代码,这本书只需使用"Paij-ree".name_significance。但当我尝试做同样的事情时,我得到了一个NoMethodError - in <top (required)>: undefined method NameReplacer for "Paij-ree":String (NoMethodError)。
当我尝试时,我得到了同样的错误:print "Paij-ree".NameReplacer.new.name_significance
我认为这在书中是可行的,因为这个方法是在String类中编写的,我猜这相当于在Ruby的String类中使用这个方法。因此,像"paij-ree".name_significance"这样的东西不会抛出错误,因为"paij-ree"将是一个String对象,而String类确实有方法name_significance。
但是,如何用我的当前代码来完成这个任务呢?如果这个问题看起来很蠢的话,我很抱歉。
发布于 2015-10-13 02:07:22
有三种方法取得了相同的结果:
# monkey-patching a class
class String
def appendFoo
self + "foo"
end
end
"a".appendFoo
# => "afoo"
# using an external class method
class FooAppender
def self.appendFoo(string)
string + "foo"
end
end
FooAppender.appendFoo("a")
# => "afoo"
# using an external instance method
class StuffAppender
def initialize(what)
@what = what
end
def append_to(string)
string + @what
end
end
new StuffAppender("foo").append_to("a")
# => "afoo"self是指定义方法的对象。不能在self类中使用NameReplacer来引用字符串,它将是NameReplacer实例(在像您这样的实例方法中)。
发布于 2015-10-13 02:11:18
正如其他人所提到的,该代码依赖于String类。对于您来说,另一种选择是使用类扩展String类,如下所示:
class NameReplacer < String
@@syllables = [
{
"Paij" => "Personal",
"Gonk" => "Business",
"Blon" => "Slave",
"Stro" => "Master",
"Wert" => "Father",
"Onnn" => "Mother"
},
{
"ree" => "AM",
"plo" => "PM"
}
]
# method to determine what a certain name of his means
def name_significance
# split string by -
parts = self.split("-")
# make duplicate of syllables
syllables = @@syllables.dup
signif = parts.collect {|name| syllables.shift[name]}
#join array returned by " " forming a string
signif.join(" ")
end
end然后像这样使用它:
p = NameReplacer.new("Paij-ree")
puts p.name_significancehttps://stackoverflow.com/questions/33092938
复制相似问题