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

前端 未结 6 1096
感动是毒
感动是毒 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:50

    I sometimes have the opposite requirement. I sometimes want to put a certain character after the joined up string. To do that, I usually do

    ["name1", "name2"].join("&") + "&"
    

    If you're wondering "Why doesn't Ruby implement the ability to add something at the beginning?", my answer is that if was going to handle that kind of scenario, there'd be too many possibilities to consider:

    1. Just have & in between elements?
    2. Have & between elements, and before the start?
    3. Have & between elements, and after the end?
    4. Have & between elements, and before the start, and after the end?
    5. Have & between elements, and \n after the end?
    6. Have ? before the elements, & between the elements, and \n after the end?
    7. Do something special if there's no elements?

    As a side note, if you're trying to build up a URL, you might want to use a library rather than do it manually.

提交回复
热议问题