Vieenay Siingh
Vieenay Siingh

Reputation: 867

how to convert array output to normal string in ruby on rails application

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?

Upvotes: 4

Views: 11235

Answers (3)

user16407989
user16407989

Reputation: 1

["social network", "professional"].join(",")

"social network,professional"

or if you don't want the comma

["social network", "professional"].join(" ")

"social network professional"

Upvotes: -1

Vieenay Siingh
Vieenay Siingh

Reputation: 867

I got two solutions which are below:

<%= article.tags.collect(&:name).join(" ")%>
<%= article.tags.pluck(:name).join(" ") %> - by yossarian.

Upvotes: 0

Christian-G
Christian-G

Reputation: 2361

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(" ")

Upvotes: 12

Related Questions