Question

I have an Array of Hashes that look like this:

texts = [{:text => 'my text', :width => 123}, {:text => 'my other text', :width => 200}]

I want to have a final text that would look like this:

my_final_text = 'my text\nmy other text'

I have tried doing this:

def concat_breakline(texts)
  final_text = ""
  texts.each do |text|
    final_text << text[:text] + "\n"
  end
end

But this would add "\n" to the last element, and I want to avoid that. How could I solve that?

Was it helpful?

Solution

It's pretty easy:

texts.collect { |text| text[:text] }.join("\n")

The join method adds things in the middle but not the end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top