RoR教程第4.1.1章,混淆了为什么标题助手不会失败

我正在阅读Michael Hartl的Ruby on Rails 3.2教程,我很困惑为什么第4.1.1节中找到的标题助手不会失败。

他谈到在你从视图中省略这段代码时需要一个标题助手:

 

但是在应用程序布局文件中有以下行:

  

是不是将nil值传递给full_title助手,因为提供者没有为:title符号设置值?

在本章的后面,他有一个键入rails控制台的示例,它与full_title函数相同:

 def string_message(string) if string.empty? "It's an empty string!" else "The string is nonempty." end end 

这使我更加困惑。

在控制台,如果我输入:

  • string_message("")然后我得到"It's an empty string!"
  • string_message("something")然后我得到"The string is nonempty."
  • string_message(nil)然后我得到NoMethodError: undefined method 'empty?' for nil:NilClass NoMethodError: undefined method 'empty?' for nil:NilClass
  • string_message(test)然后我得到ArgumentError: wrong number of arguments (0 for 2..3)
  • string_message(:test)然后我得到"The string is nonempty."

所以传递一个未定义的符号不会导致零值? 但它也不是空的? 为什么不:标题被视为非空? 如果有人能让我明白这一点,那就太好了。

虽然你的论点是“字符串”,但不要挂断它必须是一个字符串。 有人可以将任何参数传递给函数,它是否会在函数中出现问题,实际上只取决于该对象是否响应“空”? 信息。

你打电话的时候

 string_message("") 

打电话给

 "".empty? 

评估为真。

当你传递一个nil对象时,nil不支持空? 消息,所以它抛出一个错误

当你抛出任意符号时

 string_message(:pigs_on_the_wing) 

您将空消息发送到:pigs_on_the_wing,这是一个符号。 符号定义“空?” 仅当符号的主体为“”时才返回true。

例如,在irb中:

 :"".empty? # true :pigs_on_the_wing.empty? #false 

您可以随时直接访问来源:

http://www.ruby-doc.org/core-1.9.3/Symbol.html#method-i-empty-3F