ruby - 无方法错误 : Calling an instance method correctly in Ruby with the use of self

标签 ruby self instance-methods

我在阅读 Why's (Poignant) 的 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 中使用此方法类(class)。因此,类似 "paij-ree".name_significance" 的东西不会抛出错误,因为 "paij-ree"将是 String对象,和 String类确实有方法 name_significance .

但是,如何使用我当前的代码完成此操作?如果这个问题看起来很愚蠢,我们深表歉意。

最佳答案

结果相同的三种方法:

# 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 表示定义方法的对象。您不能在 NameReplacer 类中使用 self 来引用字符串,它将是 NameReplacer 实例(在像您这样的实例方法中).

关于ruby - 无方法错误 : Calling an instance method correctly in Ruby with the use of self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092938/

相关文章:

ruby-on-rails - 当其他属性发生变化时如何更新一个属性

ios - Swift - 执行 Segue

python - 我可以指定另一个类的实例方法作为我的方法的变量吗?

python - 使用父类(super class)方法作为实例方法

ruby-on-rails - 无法安装 curl gem

ruby - 在不同的进程中生成命令提示符并在 Windows 上发送/接收命令

ios - 使用self调用方法会导致错误

pickle - 不能pickle instancemethod 对象

ruby-on-rails - 如何在Peatio中添加比特币?

rust - 为什么 Iterator::filter 方法接受一个可变引用作为 self?