Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: add object to the end of array

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!

like image 773
tiswas Avatar asked Dec 14 '25 08:12

tiswas


1 Answers

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.

like image 53
etarion Avatar answered Dec 16 '25 23:12

etarion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!