The most efficient way to get a list of space delimited strings

A project can have many tags. When editing a project, I would like to list all the tags in the 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 faster / more elegant way?

@tags = @project.tags

@tags_array = []
@tags.each do |tag|
  @tags_array << tag.name
end

@tags_string = @tags_array.join(' ')
+3
source share
2 answers

Maybe you need a method Enumerable#collect:

@tags_string = @project.tags.collect(&:name).join(' ')

The collection is useful when you are trying to convert one list to another list of equal size, which is just such a pattern here.

The part &:namemeans β€œthe name of the invocation method for this object” and this is what can be indicated as { |t| t.name }equivalent.

Enumerable , , .

+6

- @tags. http://rubysource.com/threading-ruby/

-, , @tag - , ,

names = @tags.map{|tag| tag.name}.join(' ')
0

All Articles