Keren
Keren

Reputation: 217

Remove certain instance of a specific item from a string

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

Answers (6)

spickermann
spickermann

Reputation: 106852

You could use sub like this:

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

Upvotes: 1

Cary Swoveland
Cary Swoveland

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

ndipiazza
ndipiazza

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

pguardiario
pguardiario

Reputation: 54984

How about:

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

it works because the .* is greedy

Upvotes: 1

steenslag
steenslag

Reputation: 80065

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"

Upvotes: 2

Sam
Sam

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

Related Questions