1

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

他谈到如果您从视图中遗漏了这段代码,则需要一个标题助手:

<% provide(:title, 'Home') %>

但是在应用程序布局文件中有这一行:

<title><%= full_title(yield(:title)) %></title>

由于提供没有为 :title 符号设置值,这不会将 nil 值传递给 full_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
  • string_message(test)然后我得到ArgumentError: wrong number of arguments (0 for 2..3)
  • string_message(:test)然后我得到"The string is nonempty."

那么传递一个未定义的符号不会产生一个零值吗?但它也是非空的?为什么 :title 不被视为非空?如果有人可以为我解决这个问题,那就太好了。

4

1 回答 1

1

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

你打电话时

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

于 2012-02-12T04:41:13.063 回答