tags:

views:

68

answers:

3

Getting the customer's to_s method by looping through

Is there a Ruby idiom to write the code in 1 line (or shorter than 3 lines of code)?

def method
  string = ""
  @customers.each { |customer| string += customer.to_s + "\n" }
  string
end
+6  A: 
@customers.join("\n") + "\n"

join creates a string from an array by calling to_s on each element that is not already a string and inserting them into the new string separated by the parameter to join (in this case \n). Since your code also adds a \n at the end (and join does not), you need to add + "\n" after the call to join to get the same behavior.

sepp2k
thank you. It works very well.
Hadi
+2  A: 

I think you want something like

@customers.join("\n")
Michael Ulm
that works too, as sepp2k has stated, that the last bit should have "\n" also, so i need to add "\n" at the end of the join. thank you
Hadi
+1  A: 

Mostly for fun, and building off @sepp2k's answer:

"#{@customers.join "\n"}\n"

I quite like embedded string syntax, because it's easy to expand later if you want other header/footer text.

Peter