What does it mean to use the name of a class for string interpolation?

时光怂恿深爱的人放手 提交于 2019-12-11 19:24:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!