user3685089 user3685089 - 2 months ago 8
Ruby Question

Multi-line syntax in to_s with reference to an object

I have a problem constructing the to_s method.

class Personne
attr_accessor :prenom, :nom, :email, :telephone, :adresse
def initialize
@prenom = @nom = @email = @telephone = ""
@adresse = Adresse.new
end
def to_s
@prenom + ", " + @nom + "\n" + \
"Email: " + @email + "\n" + \
"Tel: " + @telephone + "\n" + \
@adresse
end
end


The @adresse is and object with very similar to_s method.
The error:

in `+': no implicit conversion of Adresse into String (TypeError)


I do not understand the issue, since address object has it's own print method.

Answer

I do not understand the issue, since address object has it's own print method.

You are passing an instance of class Adresse as an argument to + method, called on string, it throws an error, because it expects an instance of String class as an argument.

To make this work you would want to convert it to string using, for instance, to_s method.

+ @adresse.to_s # would do it for you
Comments