Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a trailing comma?

Tags:

Given strings like:

Bob Bob, Bob Bob Burns, 

How can you return that w/o a comma?

Bob Bob Bob Bob Burns 

Also, I would want this method not to break if passed a nil, just to return a nil?

def remove_trailing_comma(str)   !str.nil? ? str.replace(",") :nil end 
like image 564
AnApprentice Avatar asked Apr 30 '11 17:04

AnApprentice


People also ask

How do I get rid of trailing commas in CSV?

To remove trailing commas from your Excel cells, you can create a function that checks for a comma at the end of a string and then deletes the final character in the string if it is a comma.

How do you remove trailing commas in Java?

Here's how: str = str. replaceAll(", $", "");


2 Answers

My thought would be to use string.chomp:

Returns a new String with the given record separator removed from the end of str (if present).

Does this do what you want?

def remove_trailing_comma(str)     str.nil? ? nil : str.chomp(",") end 
like image 80
RHSeeger Avatar answered Oct 02 '22 14:10

RHSeeger


use String#chomp

irb(main):005:0> "Bob".chomp(",") => "Bob" irb(main):006:0> "Bob,".chomp(",") => "Bob" irb(main):007:0> "Bob Burns,".chomp(",") => "Bob Burns" 

UPDATE:

def awesome_chomp(str)     str.is_a?(String) ? str.chomp(",") : nil end p awesome_chomp "asd," #=> "asd" p awesome_chomp nil #=> nil p awesome_chomp Object.new #=> nil 
like image 22
Vasiliy Ermolovich Avatar answered Oct 02 '22 15:10

Vasiliy Ermolovich