开发者

How to remove a trailing comma?

开发者 https://www.devze.com 2023-03-02 00:18 出处:网络
Given strings like: Bob Bob, Bob Bob Burns, How can you return that w/o a comma? Bob 开发者_JAVA百科Bob

Given strings like:

Bob
Bob,
Bob
Bob Burns,

How can you return that w/o a comma?

Bob
开发者_JAVA百科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


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


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


You could do something like this:

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


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.


you could use

str.delete_suffix(',')
0

精彩评论

暂无评论...
验证码 换一张
取 消