为什么单词’translate’会弄乱irb?

我不明白为什么我的方法translate undefines start_with? 方法,并在irb中搞乱一些东西,所以我只能通过按Ctrl + d退出irb,而不是exitquit

 >> "hello".respond_to?(:start_with?) => true >> def translate(string) >> if string.start_with?("a", "e", "i", "o", "u") >> string += "ay" >> end >> end NoMethodError: undefined method `start_with?' for # from (irb):3:in `translate' from /usr/local/rvm/rubies/ruby-2.3.0/bin/irb:11:in `' >> "hello".respond_to?(:start_with?) NoMethodError: undefined method `start_with?' for :RubyVM::InstructionSequence from (irb):3:in `translate' from /usr/local/rvm/rubies/ruby-2.3.0/bin/irb:11:in `' >> exit NoMethodError: undefined method `start_with?' for :RubyVM::InstructionSequence from (irb):3:in `translate' from /usr/local/rvm/rubies/ruby-2.3.0/bin/irb:11:in `' >> quit NoMethodError: undefined method `start_with?' for :RubyVM::InstructionSequence from (irb):3:in `translate' from /usr/local/rvm/rubies/ruby-2.3.0/bin/irb:11:in `' >> 

我尝试了两个不同的工作区,效果是一样的。
我的Ruby和Rails版本是:

 ~/workspace $ ruby -v ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux] ~/workspace $ rails -v Rails 4.2.2 

从我的另一个问题我知道许多I18N图书馆使用了单词translate ,所以这是我唯一的嫌疑人,因此这个问题的标题。 但作为初学者,我没有看到任何关系。

YARV中的一个错误是在YARV 2.4.0中修复的 。

如果您没有YARV 2.4.0,则提交消息会提及以下解决方法:

 class << RubyVM::InstructionSequence def translate; end undef translate end 

请注意,其他实现不受影响,仅限YARV。

这是一个理论

  • 您的设置中可能还有一个全局functiontranslate
  • irb打印输出时,使用指令序列作为参数调用此函数
  • 因此,当您重新定义translate打印时,输出会中断

NoMethodError: undefined method并不意味着该方法已全局未定义,而是发送给不理解它的对象

你可以通过执行来测试我的理论

 method(:translate) 

如果你得到一个结果,那么已经定义了translate ,你不能重新定义它!

现在如果你想知道哪个gem定义了这个函数,安装pry gem(这是一个更好的irb)并使用$命令来查看该方法的文件和源代码

 # Use this command in pry to see location and source code $ translate