Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am implementing tag functionality and an article may have one to many tags. I am able to get tag values from db in this format

["social network", "professional"]

I want output in this format

"social network professional"

I want to convert an array into a string without ,. Below is a code snippet which takes out values from db as an array.

<%= article.tags.collect(&:name) %>

How can I convert this output into string value(s) with out any comma?

share|improve this question

2 Answers

up vote 1 down vote accepted

Did you look at pluck? This if very useful for if you want just one record from the db (in your case 'name'). You could use that to do this:

a = article.tags.pluck(:name)

To then output your article names separated by spaces do this:

a.join(" ")

For completeness sake, you can chain these methods (like you said in the comment below) like this:

article.tags.pluck(:name).join(" ")
share|improve this answer
hi yossarian thanks. will it work in case of fetching multiple values from db. – VSiingh Apr 13 at 12:55
Yes, for multiple values this works. pluck however only retrieves ONE database field. If you need more use collect like you did. (or select) – yossarian Apr 13 at 12:56
If this answered your question, please accept so future readers know it did – yossarian Apr 13 at 13:01
It worked for me like <%= article.tags.pluck(:name).join(" ") %>. Thanks yossarian. – VSiingh Apr 13 at 13:03
hi yossarian, even <%= article.tags.collect(&:name).join(" ") works fine. – VSiingh Apr 13 at 13:14
show 2 more comments

I got two solutions which are below:

<%= article.tags.collect(&:name).join(" ")%>
<%= article.tags.pluck(:name).join(" ") %> - by yossarian.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.