简体   繁体   中英

Methods to concatenate strings on separate lines

This produces newlines:

%(https://api.foursquare.com/v2/venues/search
                          ?ll=80.914207,%2030.328466&radius=200
                          &v=20161201&m=foursquare&categoryId=4d4b7105d754a06374d81259
                          &intent=browse)

This produces spaces:

"https://api.foursquare.com/v2/venues/search
 ?ll=80.914207,%2030.328466&radius=200
 &v=20161201&m=foursquare&categoryId=4d4b7105d754a06374d81259
 &intent=browse"

This produces one string:

"https://api.foursquare.com/v2/venues/search"\
"?ll=80.914207,%2030.328466&radius=200"\
"&v=20161201&m=foursquare&categoryId=4d4b7105d754a06374d81259"\
"&intent=browse"

When I want to separate one string on multiple lines to read it better on screen, is it preferred to use the escape character?

My IDE complains that I should use single quoted strings rather than double quoted strings since there is no interpolation.

Normally you'd put something like this on one line, readability be damned, because the alternatives are going to be problematic. There's no way of declaring a string with whitespace ignored, but you can do this:

url = %w[ https://api.foursquare.com/v2/venues/search
  ?ll=80.914207,%2030.328466&radius=200
  &v=20161201&m=foursquare&categoryId=4d4b7105d754a06374d81259
  &intent=browse
].join

Where you explicitly remove the whitespace.

I'd actually suggest avoiding this whole mess by properly composing this URI:

uri = url("https://api.foursquare.com/v2/venues/search",
  ll: [ 80.914207,30.328466 ],
  radius: 200,
  v: 20161201,
  m: 'foursquare',
  categoryId: '4d4b7105d754a06374d81259',
  intent: 'browse'
)

Where you have some kind of helper function that properly encodes that using URI or other tools. By keeping your parameters as data, not as encoded strings, for as long as possible you make it easier to spot bugs as well as make last-second changes to them.

The answer by @tadman definitely suggests the proper way to do it; I'll post another approach just for the sake of diversity:

query = "https://api.foursquare.com/v2/venues/search"
        "?ll=80.914207,%2030.328466&radius=200"
        "&v=20161201&m=foursquare&categoryId=4d4b7105d754a06374d81259"
        "&intent=browse"

Yes, without any visible concatenation, 4 strings in quotes one by one in a row. This example won't work in irb / pry (due to it's REPL nature,) but the above is the most efficient way to concatenate strings in ruby without producing any intermediate result.


Contrived example to test in pry / irb :

value = "a" "b" "c" "d"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM