0

Is there a way to remove a specific instance of an item from a string? For example, if I have the string:

"kiwi, durian, and, starfruit"

how can I remove the final comma only? I need a solution that will remove the last comma from the string no matter how many items the string contains.

Couldn't find anything at all on this by Googling around (at least not for Ruby without Rails. If you're using Rails, it's easy--just use the array.to_sentence method.)

2
  • Welcome to Stack Overflow. When asking, you need to show where you've searched and why those didn't apply, or show code you've tried and explain why it doesn't work. As is, it looks like you're asking us to write something for you, and Stack Overflow isn't a "write code for me site". Instead, we help you debug problems in your code. Commented Nov 20, 2015 at 22:18
  • @theTinMan Understood, I added what I tried as well as a solution I found for anyone using Rails. Thanks. Commented Nov 21, 2015 at 14:18

6 Answers 6

2

You could reverse the string, sub a comma for "", and reverse it again. But rindexis nice too:

str = "kiwi, durian, and, starfruit"
str.slice!(str.rindex(","))

p str # => "kiwi, durian, and starfruit"
Sign up to request clarification or add additional context in comments.

5 Comments

@theTinMan I agree, []= is better.
Speedwise, they're a wash. I checked with Fruity and it says the speed difference is negligible so it probably comes down to team programming style and programmer's choice. Plus, avoiding the use of a regular expression improves the speed over regex-based sub and gsub.
This will bomb for a string with no commas. Also I think we're underestimating regex performance. Regex is very fast.
This returned "," for me. The only answer that worked was the one I marked as correct. Thanks for your help!
@Keren it reurns a comma and it modifies str.
1

You could use sub like this:

"kiwi, durian, and, starfruit".sub(/,([^,]*)\z/, '\1')
#=> "kiwi, durian, and starfruit"

3 Comments

Worth a special commendation as a code golf worthy answer! nice one.
$1 doesn't do here what you think it does. You want '\1'. Also what about non-word chars?
gsub is slower than sub.
1

How about:

"kiwi, durian, and, starfruit".sub /(.*),/, '\1'
#=> "kiwi, durian, and starfruit"

it works because the .* is greedy

9 Comments

While sub is faster than gsub, relying on a regex is costly unless the regex is anchored. And, even then, they tend to lose-out to using the built-in methods.
@the Tin Man - it's not a race! :) also I don't know why you think an anchor would help but I guess it couldn't hurt.
I think anchors help because I've tested patterns with and without them, and there's a major speed-up if the engine knows to start at the beginning or end of the string.
Hmm, I think you're misunderstanding something fundamental. The regex engine always starts at the beginning of the string.
I know that it starts at the beginning. If the value we're after is at or near the end, then an anchor can make a huge difference, especially for long strings.
|
0

String to array split on the commas, then re join all but the last items with a comma and add the final part of the array back on.

string = "kiwi, durian, and, starfruit"
array = string.split","
pre = array.slice(0,array.length - 1).join","
post = array[array.length - 1]
output = pre + post
p = output

Comments

0

There being five answers over nine hours, all that's left are crumbs. Here's one:

str = "kiwi, durian, and, starfruit"

str[str[/.*,/].size-1] = ''
str #=> "kiwi, durian, and tarfruit" 

Comments

-1

If the string always includes "and" you could use gsub.

new_string = "kiwi, durian, and, starfruit".gsub("and,", "and")

Otherwise you could write a function like this:

def strip_last_comma string
  spt_str = string.split(",")
  string = spt_str[0..spt_str.size-2].join(",") + spt_str.last
end

3 Comments

gsub will always run slower than using sub when you're only replacing one thing.
I don't know if sub is really faster than gsub but it's useful as a clue that we're only replacing one thing.
"I don't know if sub is really faster than gsub...". Benchmarks show us these things. Sometimes the situation somewhat nullifies the advantage, such as when replacing something at the end of a string, however, in general sub only tries to replace once, where gsub will try at least once more and if the string being searched is really long and the first hit was at the start, the resulting second search will waste CPU.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.