Reputation: 217
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.)
Upvotes: 0
Views: 100
Reputation: 106852
You could use sub
like this:
"kiwi, durian, and, starfruit".sub(/,([^,]*)\z/, '\1')
#=> "kiwi, durian, and starfruit"
Upvotes: 1
Reputation: 110675
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"
Upvotes: 0
Reputation: 69
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
Upvotes: -1
Reputation: 54984
How about:
"kiwi, durian, and, starfruit".sub /(.*),/, '\1'
#=> "kiwi, durian, and starfruit"
it works because the .*
is greedy
Upvotes: 1
Reputation: 80065
You could reverse
the string, sub
a comma for ""
, and reverse
it again.
But rindex
is nice too:
str = "kiwi, durian, and, starfruit"
str.slice!(str.rindex(","))
p str # => "kiwi, durian, and starfruit"
Upvotes: 2
Reputation: 650
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
Upvotes: 0