سؤال

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?

هل كانت مفيدة؟

المحلول

It's pretty easy:

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top