4

When using Objects returned by the ActiveRecord collection proxy, using a loop if fine in a view, but sometimes I want to turn just one of the hash' common attributes into an array. I find I'm doing it a lot, which results in what appears to be somewhat verbose:

 forum_roles = []

 @forum #=> [{id: 0, name: 'a'},{id: 1, name: 'b'}]

 @forum.each do |role|
    forum_roles << role.name
 end

 forum_roles #=> ['a','b']

Just wondering if there's an easier way to arriving at ['a','b']

1 Answer 1

5

Use Array#map when you have an array of hashes

forum_roles = @forum.map { |role| role[:name] }
forum_roles # ['a','b']

UPDATE:

With ActiveRecord Objects, there's a shorcut as @vee commented

@forum.map(&:name)

If you have an ActiveRecord Relation and you only want an array of a column, use pluck

@forum.pluck(:name)
Sign up to request clarification or add additional context in comments.

4 Comments

@vee &:name isn't correct. That invokes role.name() on each hash, not role[:name]. That would work for an array of objects, but not an array of hashes.
@meagar, but @forum is an AR Relation, so isn't it safe to assume name is an attribute of presumably Role object?
@meagar the title of the question is misleading. reading the body will tell us that @forum is indeed an AR relation which is why the OP can do forum_roles << role.name
Wow, pluck is plucking amazing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.