Ruby: add object to the end of array
-
26-10-2019 - |
Pergunta
I have two objects @tracks (an enumerable) and @artist, and I'd like to create an enumerable with all the tracks and the artist in them. This is so that I can pass them to a method which will do (each track, and the artist have change events):
change_events = object.map(&:change_events).flatten
My idea was:
objects = @artist.tracks
objects << @artist
but that gives me this error for the second line (which makes sense, but I don't know how to fix):
Track(#17816) expected, got Artist(#17572)
Any ideas on how I could do this would be appreciated!
Solução
This (the error) signals that it (the return value of @artist.tracks
) is not an array you are dealing with, but some rails-specific data type. You could try
objects = @artist.tracks.to_a
objects << @artist
But using inhomogeneous values in an array is often not good, if they all respond to the method you need you should be good though.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow