Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

ruby

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
like image 222
Hadi Avatar asked Feb 19 '26 22:02

Hadi


1 Answers

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

like image 72
sepp2k Avatar answered Feb 21 '26 12:02

sepp2k