simonmorley
simonmorley

Reputation: 2804

Converting an array into string

I need to join output of a hash into a string.

The hash looks like this:

 nas.location.walledgardens.to_s

  => "[#<Walledgarden id: 1, location_id: 12, url: \"polka.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 2, location_id: 12, url: \"test.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 3, location_id: 12, url: \"help.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 4, location_id: 12, url: \"yell.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 5, location_id: 12, url: \"sausage.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">]" 

I need to join the url values into the following format:

polka.com,test.com,help.com

What the best way to do this? I can easily look through it but the output has line breaks and I need these removed plus the commas.

Upvotes: 1

Views: 4465

Answers (3)

Hauleth
Hauleth

Reputation: 23556

Use Array#map:

nas.location.walledgardens.map(&:url).join ','

Upvotes: 4

jtbandes
jtbandes

Reputation: 118651

What you have is not a Hash, but an Array of Walledgarden objects (they look to be ActiveRecord::Base subclasses).

Try this:

nas.location.walledgardens.collect(&:url).join ","

(Note: #map and #collect are equivalent, so which one you choose should be a consideration of readability!)

Upvotes: 6

MrDanA
MrDanA

Reputation: 11647

nas.location.walledgardens.collect { |w| w.url }.join(",")

The .collect method will collect all what that block returns and put it in an array, and then the join puts that array in a string, separated by whatever you give it (so a comma).

Upvotes: 6

Related Questions