开发者

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

开发者 https://www.devze.com 2023-02-12 18:47 出处:网络
I am using Ruby on Rails 3 and I am trying join an array with the & character开发者_如何转开发. I read the Ruby documentation about that.

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:

["name1", "name2"]

If I do

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

it results as

name1&name2

I would like that results as

&name1&name2 # Note the first "&"

A solution is

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

but I think it is not a "right way".

So, how can I have &name1&name2 without using ["", "name1", "name2"].join("&")?


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


["name1", "name2"].join('&').prepend('&')


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


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.


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

"&#{["name1","name2"].join("&")}"


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

精彩评论

暂无评论...
验证码 换一张
取 消