When using puts exits only the address, and not the expected message

Asked

Viewed 52 times

1

Hello, I’m starting with the ruby language and I find the following problem that is at the time of printing message through to_s:

main class

require File.expand_path("lib/Livro")

biblioteca = []

instancia = Livro.new "Ruby", "X", "Casa do Código", 56.40
instancia_dois = Livro.new "Java", "Y", "Casa do Código", 78.9

biblioteca << instancia
biblioteca << instancia_dois

puts biblioteca

accessed class

class Livro

    attr_accessor :preco,:autor,:editora,:nome

    def initialize nome_livro, autor,_editora = nil, preco
      @nome = nome_livro
      @autor = autor
      @editora = editora
      @preco = preco    
    end

    def to_s
      "Autor: #{@nome}, Autor: #{@autor}, Editora: #{@editora},Preço: #{@preco}"
    end
end 

In the code output instead of the message attached in to_s appears only the addresses of the objects, I tried to search on the internet but n found nothing that could help thanks from now.

  • Do so library.map(&:to_s) As you are starting I will give you a hint, access the Ruby style guide to learn how to format the code with some patterns. Hug.

  • I’m glad my reply was helpful! Thank you.

1 answer

0


Hello I checked your code here and it worked:

Instantiating the class

class Livro

 attr_accessor :preco,:autor,:editora,:nome    

 def initialize nome_livro, autor,_editora = nil, preco    
   @nome = nome_livro      
   @autor = autor      
   @editora = editora      
   @preco = preco          
 end      

 def to_s    
   "Autor: #{@nome}, Autor: #{@autor}, Editora: #{@editora},Preço: #{@preco}"      
 end      
end   

And running the tests:

biblioteca = []

instancia = Livro.new "Ruby", "X", "Casa do Código", 56.40
=> #<Livro:0x00000001f18aa0 @autor="X", @editora=nil, @nome="Ruby", @preco=56.4>
instancia_dois = Livro.new "Java", "Y", "Casa do Código", 78.9
=> #<Livro:0x00000001e71688 @autor="Y", @editora=nil, @nome="Java", @preco=78.9>

biblioteca << instancia
=> [#<Livro:0x00000001f18aa0 @autor="X", @editora=nil, @nome="Ruby", @preco=56.4>]
biblioteca << instancia_dois
=> [#<Livro:0x00000001f18aa0 @autor="X", @editora=nil, @nome="Ruby", @preco=56.4>, #<Livro:0x00000001e71688 @autor="Y", @editora=nil, @nome="Java", @preco=78.9>]

puts biblioteca
Autor: Ruby, Autor: X, Editora: ,Preço: 56.4
Autor: Java, Autor: Y, Editora: ,Preço: 78.9

I ran everything directly on the console.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.