views:

26

answers:

3

Hi,

I have a string:

"116,118,120,130"

and will want to delete either the first, last or any value in between upon execution.

To to this I was using:

"116,118,120,130".gsub('118','')

but the problem is the string contains an extra unnessesary comma:

"116,,120,130"

and if I use

"116,118,120,130".gsub(',116','')

it will remove the comma, but then won't match "116" in the string as there is no comma in front of "116"

How can I match parts of my string that may or my not have the comma in front of value I am removing elegantly?

Thanks,

+2  A: 

Hmm, I might try something like...

"116,118,120,130".split(',').reject{|e|e=="116"}.join(',')
DigitalRoss
+1 This is probably the easiest way to do it. Split the string into an array (breaking at the commas), then remove whatever you don't want, then re-assemble the array into a comma-delineated string. While it's probably possible to do the same with `gsub` or similar, this method seems much less error-prone.
bta
A: 

Well, there are two easy ways to do this. First, you can use a regular expression. A simple one like:

"116,118,120,130".gsub(/(,118)|(118,)/,'')

Will do what you want. With 118 replaced by whatever value you are looking for. But if you are looking for more then 1 value, why not just split and recombine it. For example

"116,118,120,130".split(',').reject {|val| val == '118' || val == '130'}.join(',')

Returns "116,120"

ScottD
A: 

If it's slightly more complicated CSV data (e.g. it has embedded commas), use the csv standard library module

require 'csv'
str = 'abc,def,"ghi,jlk",mno'
fields = CSV.parse_line(str)
fields.reverse!  # or do whatever manipulation
new_line = CSV.generate_line(fields) 
# => "mno,\"ghi,jlk\",def,abc\n"
glenn jackman