Hadi
Hadi

Reputation: 103

Looping through an array while adding the data to a string and finally returning it, a faster way?

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

Upvotes: 2

Views: 305

Answers (3)

Peter
Peter

Reputation: 132197

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.

Upvotes: 1

Michael Ulm
Michael Ulm

Reputation: 802

I think you want something like

@customers.join("\n")

Upvotes: 2

sepp2k
sepp2k

Reputation: 370112

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

Upvotes: 6

Related Questions