A project can have many tags. When editing a project I’d like to list all tags in a input field (stackoverflow style). In Rails 3 I have the following code, where I push all my names into an array before calling join(' ') but is there a quicker / more elegant way?
@tags = @project.tags
@tags_array = []
@tags.each do |tag|
@tags_array << tag.name
end
@tags_string = @tags_array.join(' ')
Maybe what you want is the
Enumerable#collectmethod:Collect comes in handy when you’re trying to transform one list into another list of equal size, which is exactly the pattern here.
The
&:namepart means “call method name on the given object” and is something that could be spelled out as{ |t| t.name }equivalently.The Enumerable library is really great and you should have a look through it and be familiar with the various methods as it can save you a ton of time.