How can I 'join' an array adding to the beginning of the resulting string the first character to join?

前端 未结 6 1054
感动是毒
感动是毒 2021-01-21 06:11

I am using Ruby on Rails 3 and I am trying join an array with the & character. I read the Ruby documentation about that.

My array is:

6条回答
  •  猫巷女王i
    2021-01-21 06:41

    Another alternative solution: you could use Enumerable#inject to build a string.

    ["name1", "name2"].inject("") { |str, elem| str += "&#{elem}" }
    

    [Edit]

    To be a completionist, I must add that you shouldn't forget that modifying a string over and over can give poor performance if you do it many, many times. If you have a large array, you can use a StringIO:

    require 'stringio'
    ["name1", "name2"].inject(StringIO.new) { |str, elem| str << "&#{elem}" }.to_s
    

提交回复
热议问题