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

前端 未结 6 1046
感动是毒
感动是毒 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条回答
  • 2021-01-21 06:33

    The whole point of join is that you only get characters between the joined items. You want one in front of every item. I don't know of a short way, but it seems more natural just to map them and then join them without a delimiter:

    ["name1", "name2"].map{|item| '&'+item}.join
    
    0 讨论(0)
  • 2021-01-21 06:34

    Join is meant to not prepend a string. Here's another option:

    "&#{["name1","name2"].join("&")}"
    
    0 讨论(0)
  • 2021-01-21 06:37
    ["name1", "name2"].join('&').prepend('&')
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-21 06:50

    A slightly modified form of the answer you provided may be less computationally intensive, given the size of your array.

    (['']+Array.wrap(classes)).join('&')
    

    This works for whether classes is a type Array

    0 讨论(0)
提交回复
热议问题