0

I seem to be writing quite a few methods with the following pattern and it seems like there should be a better way. Is there a one-liner for this or a better practice?

def combine_roster(roster)
  rstr = []
  roster.each do |r|
    rstr << r.user
  end
  rstr
end
3

1 Answer 1

5

Yes, you can use the map command. Here is the short hand version for what you are trying to do:

roster.map(&:user) # if roster = [r1, r2, r3] then the output will be [r1.user, r2.user, r3.user]

You can read more about the map function in the Ruby Array API: http://ruby-doc.org/core-2.0.0/Array.html#method-i-map

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.