How should an array be applied to another array (or collection) to return records at particular indexes?
I have an active record set corresponding to some records and I want to pull particular members by index in the collection from this result (i.e. I want the 2nd, 4th and 5th record)
While this works fine:
random_members = club.users[1,3,5]
This does not:
selected_indices = [1,3,5]
random_members = club.users(selected_indices)
I need the second method since the indices I'm using are generated.
In the first case Ruby is clearly taking applying the indices to the collection but in the second it's trying to use the array as a method argument. This is more of a Ruby question than a rails question however I have no idea what operator to use apply the array to the collection rather than calling it as a method.
NB The indices are the positions of the members in the active record set and n开发者_如何学编程ot the ID of the actual members.
Try this:
selected_indices = [1,3,5]
random_members = club.users[*selected_indices]
*
is called the splat operator and allows you to use the contents of an array as parameters. Think of it as the contents of the array without the []
.
Here is my solution using a proc as a workaround
selected_indices = [1,3,5]
selected_users = selected_indices.map{|x| club.users[x]}
This uses a map proc to iterate through the array and do a slice for each array item. It might not be exactly what you want but it does what you need.
精彩评论