问题
The following code is an extract from rubykoans about_classes.rb:
class Dog7
def initialize(initial_name)
@name = initial_name
end
def to_s
@name
end
end
I created an instance of Dog7:
fido = Dog7.new("Fido")
I understand the following:
"My dog is " + fido.to_s # => "My dog is Fido"
"My dog is #{fido.to_s}" # => "My dog is Fido"
I do not understand why the following interpolation makes sense and gives the same result:
"My dog is #{fido}" # => "My dog is Fido"
fido is not a string.
回答1:
The statement #{fido} implicitly calls fido.to_s. That's why you get the "Fido", which is the value of @name.
Actually, "My dog is #{fido.to_s}" is redundant, because the #{} bit will call to_s.
Here is another way of formatting strings:
"My dog is %s" % fido
This is pretty much another version of the #{} syntax. Above, the %s indicates to the formatter that it needs to call to_s on fido. It would be redundant to do "My dog is %s" % fido.to_s, however, it would still work.
来源:https://stackoverflow.com/questions/31521756/what-does-it-mean-to-use-the-name-of-a-class-for-string-interpolation