-1

When I run the command I get all the song names and then the instances following it. How do I only get the names?

class Song 
    @@all = [] 
    attr_accessor :name 

    def initialize(name)
        @name = name
        @@all << self    
    end 

    def self.all
        @@all  
    end

    def self.print_all_song_names
        @@all.each do |song|
        puts song.name 
        end  
    end 
end 


hotline_bling = Song.new("Hotline Bling")
thriller = Song.new("Thriller")

ninety_nine_problems = Song.new("99 Problems")
thriller = Song.new("Thriller")


puts Song.print_all_song_names 

Which outputs:

Hotline Bling
Thriller
99 Problems
Thriller
#<Song:0x00000000058ced30>
#<Song:0x00000000058cecb8>
#<Song:0x00000000058cebc8>
#<Song:0x00000000058ceb50> 
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • 1
    Change `@@all.each do |song|` to `@@all.map do |song|`. Related question: [How to understand Ruby's .each and .map](https://stackoverflow.com/questions/39146134/how-to-understand-rubys-each-and-map) – builder-7000 Apr 12 '20 at 04:47

1 Answers1

0

The issue with your code is your calling puts here and there.

The code already calls puts in print_all_song_names, and after you call puts Song.print_all_song_names which roughly means call the method and print the value returned.

each returns a receiver, which means print_all_song_names returns the value of @@all class variable. Which gets printed again.

To fix it, just don’t call puts in the last line; Song.print_all_song_names already prints out everything needed.

Song.print_all_song_names # voilà
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160