37

I have string: @address = "10 Madison Avenue, New York, NY - (212) 538-1884" What's the best way to split it like this?

<p>10 Madison Avenue,</p>
<p>New York, NY - (212) 538-1884</p>
peresleguine
  • 2,343
  • 2
  • 31
  • 34

4 Answers4

77

String#split has a second argument, the maximum number of fields returned in the result array: http://ruby-doc.org/core/classes/String.html#M001165

@address.split(",", 2) will return an array with two strings, split at the first occurrence of ",".

the rest of it is simply building the string using interpolation or if you want to have it more generic, a combination of Array#map and #join for example

@address.split(",", 2).map {|split| "<p>#{split}</p>" }.join("\n")
Pascal
  • 5,879
  • 2
  • 22
  • 34
  • I couldn't get my view to render correctly with this answer, but after adding simple_format before @address, it now returns the strings on separate lines. It took me a bit of searching to find the answer [here](http://stackoverflow.com/questions/5328235/how-to-produce-change-line-character-in-rails-view-html-erb-file/5328286#5328286) so thought I'd share it. Cheers – jfdimark Feb 21 '13 at 11:20
  • Amazing. Never knew about this, but this will save me so much time! – kobaltz Dec 14 '13 at 19:00
  • Really great feature, today only came to know split will accept second parameter that will control no of items returned from the resulted array. – Madhan Ayyasamy Dec 31 '15 at 11:16
1
break_at = @address.index(",") + 1
result = "<p>#{@address[0, break_at]}</p><p>#{@address[break_at..-1].strip}</p>"
Dogbert
  • 212,659
  • 41
  • 396
  • 397
1

rather:

break_at = @address.index(", ")
result = "<p>#{@address[0, break_at+1]}</p><p>#{@address[break_at+1..-1]}</p>"
0

Even though @address.split(",",2) is correct. Running a benchmark for split, partition and a regex solution such as @adress.match(/^([^,]+),\s*(.+)/) showed that partition is a bit better than split.

On a 2,6 GHz Intel Core i5, 16 GB RAM computer and 100_000 runs: user system total real partition 0.690000 0.000000 0.690000 ( 0.697015) regex 1.910000 0.000000 1.910000 ( 1.908033) split 0.780000 0.010000 0.790000 ( 0.788240)

mrnovalles
  • 353
  • 3
  • 7