What does using a class name to interpolate strings mean?

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 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 not a string.

0
source share
1 answer

The statement #{fido}implicitly calls fido.to_s. That is why you get "Fido" whose meaning @name.

In fact, it "My dog is #{fido.to_s}"is redundant since the bit #{}is causing to_s.

Here is another way to format strings:

"My dog is %s" % fido

#{}. , %s , to_s fido. "My dog is %s" % fido.to_s, .

+6

Source: https://habr.com/ru/post/1607842/


All Articles