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
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
@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.
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.