3

The code below works fine. But it seem clunky.

How would you combine the following code into one line?

data = Array.new
@results.each{ |result| data.push(result.get_output) }
data.join("\n")     

Ruby 1.9.3

2
  • 1
    Are you running out of lines? I can send you some more if you like... :) Jun 25 2012 at 1:06
  • I thought there must be a better, more eloquent way. Using {}.join
    – B Seven
    Jun 25 2012 at 1:12
9

Map the original collection instead of creating a new array first:

@results.map(&:get_output).join("\n")
3

I haven’t checked this, but try something like:

data = @results.map{ |result| result.get_output }.join("\n")  
3
  • 1
    Strictly speaking, this isn't the same as data never contained the joined array, just the array and had join called on it. But that may just be me being pedantic. Jun 25 2012 at 1:15
  • @AndrewMarshall yep, you’re right. I was assuming this intention as the last line isn’t mutating anything, so it must be at the end of a method and returning that anyway. Jun 25 2012 at 1:45
  • @EdwardOcampo-Gooding Yes, the last line isn't mutating anything. This is the whole method. I should have put def and end in the question.
    – B Seven
    Jun 25 2012 at 1:49
2
data = @results.collect(&:get_output).join("\") 
  1. Use collect (or map) to create an array
  2. (&:get_output), is equivalent to `collect{|result| result.get_output}
  3. chain join to the end of the results to format it

If you get empty lines, add compact before join. This helps clean up the results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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