AnApprentice
AnApprentice

Reputation: 111040

How to remove a trailing comma?

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

Upvotes: 27

Views: 23111

Answers (5)

Qd1y
Qd1y

Reputation: 21

you could use

str.delete_suffix(',')

Upvotes: 1

Redithion
Redithion

Reputation: 1016

As everyone said, chomp will do the trick.
Starting from Ruby 2.3 you can use the safe navigation operator like this: str&.chomp(','). It will only execute chomp if str is not nil, otherwise it will return nil.

Upvotes: 1

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

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

Upvotes: 7

RHSeeger
RHSeeger

Reputation: 16282

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

Upvotes: 47

robbrit
robbrit

Reputation: 17960

You could do something like this:

str && str.sub(/,$/, '')

Upvotes: 3

Related Questions