1

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.

2
  • require 'csv'; nas.location.walledgardens.map(&:url).to_csv ? Commented May 14, 2012 at 20:24
  • @SeamusAbshere IMO, loading a CSV library is overkill for this simple example. But perhaps the OP is looking to apply this in a situation where the string needs to be parsed again later — in which case that's definitely a good idea. Commented May 14, 2012 at 20:31

3 Answers 3

6
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).

Sign up to request clarification or add additional context in comments.

3 Comments

Actually Hauleth's map is better!
@MrDanA: Well map is just an alias for collect and &:url is just the Symbol#to_proc shortcut for your block, so in essence it's the same solution. :-)
@MichaelKohl I had no idea it was just a short cut like that, but it mainly just looks so much nicer. Thanks for the info though!
6

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!)

1 Comment

@phrogz! Yeah, you lot were too quick :) Thanks again
4

Use Array#map:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.