How can I "join" to an array that appends the first character to join to the beginning of the result string?

I am using Ruby on Rails 3 and I am trying an joinarray with a symbol &. I read the Ruby documentation about this .

My array:

["name1", "name2"]

If i do

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

this is the result as

name1&name2

I would like these results to be

&name1&name2 # Note the first "&"

Decision

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

but I think this is not the "right way".

So how can I &name1&name2not use ["", "name1", "name2"].join("&")?

+3
source share
6 answers

, . . , , :

["name1", "name2"].map{|item| '&'+item}.join
+12

, . :

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

: Enumerable#inject .

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

[]

, , , , . , StringIO:

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

. .

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

: " Ruby - ?", , , :

  • & ?
  • & ?
  • & ?
  • & , , ?
  • & \n ?
  • ? , & \n ?
  • - , ?

, URL-, , .

+1
source

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

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

It works whether classestypeArray

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

Source: https://habr.com/ru/post/1793394/


All Articles