问题
I'm going through Michael Hartl's Ruby on Rails 3.2 Tutorial and I'm confused about why the title helper found in Section 4.1.1 doesn't fail.
He talks about needing a title helper in the event that you leave out this bit of code from the view:
<% provide(:title, 'Home') %>
But in the application layout file there is this line:
<title><%= full_title(yield(:title)) %></title>
Doesn't that pass a nil value to the full_title helper since the provide isn't setting a value to the :title symbol?
Later in the chapter he has an example that is typed into the rails console which is the same as the full_title function:
def string_message(string)
if string.empty?
"It's an empty string!"
else
"The string is nonempty."
end
end
This confused me further.
At the console, if I type:
string_message("")
then I get"It's an empty string!"
string_message("something")
then I get"The string is nonempty."
string_message(nil)
then I getNoMethodError: undefined method 'empty?' for nil:NilClass
string_message(test)
then I getArgumentError: wrong number of arguments (0 for 2..3)
string_message(:test)
then I get"The string is nonempty."
So passing an undefined symbol does not result in a nil value? But it's also non-empty? Why isn't :title treated as non-empty? If someone could set me clear this up for me that would be great.
回答1:
While your argument is "string", don't get hung up on the idea that this has to be a string. Someone could pass any argument to the function, and whether it will have problems in your function or not really only depends on whether that object responds to the "empty?" message.
When you call
string_message("")
the call to
"".empty?
evaluates to true.
When you pass a nil object, nil doesn't support the empty? message, so it throws an error
When you throw an arbitrary symbol
string_message(:pigs_on_the_wing)
you are sending the empty message to :pigs_on_the_wing, which is a symbol. Symbol defines the "empty?" message as returning true only when the body of the symbol is "".
For example, in irb:
:"".empty? # true
:pigs_on_the_wing.empty? #false
You can always go straight to the source:
http://www.ruby-doc.org/core-1.9.3/Symbol.html#method-i-empty-3F
来源:https://stackoverflow.com/questions/9246344/ror-tutorial-chapter-4-1-1-confused-why-title-helper-doesnt-fail