Ruby:将对象添加到数组末尾

发布于 2024-10-14 17:58:47 字数 408 浏览 4 评论 0原文

我有两个对象@tracks(可枚举)和@artist,我想创建一个包含所有曲目和其中艺术家的可枚举对象。这样我就可以将它们传递给一个可以执行的方法(每个曲目和艺术家都有更改事件):

change_events = object.map(&:change_events).flatten

我的想法是:

objects = @artist.tracks
objects << @artist

但这给了我第二行的错误(这是有道理的,但我不知道如何解决):

Track(#17816) expected, got Artist(#17572)

任何关于我如何做到这一点的想法将不胜感激!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒绊 2024-10-21 17:58:47

这个(错误)表明它(@artist.tracks的返回值)不是您正在处理的数组,而是一些特定于rails的数据类型。您可以尝试

objects = @artist.tracks.to_a
objects << @artist

但是在数组中使用非齐次值通常不好,如果它们都响应您需要的方法,那么您应该会很好。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文