2011-04-30 140 views
16

给出一个字符串,如:如何删除尾随逗号?

Bob 
Bob, 
Bob 
Bob Burns, 

你怎么可以返回W/O逗号?

Bob 
Bob 
Bob 
Bob Burns 

另外,我想这个方法不破坏如果传递一个零,只是返回一个零?

def remove_trailing_comma(str) 
    !str.nil? ? str.replace(",") :nil 
end 
+0

您提供的代码不起作用,因为您的逗号周围没有引号,它是'!str.nil? ?'不''str.nil?'。请使用IRB下次检查您的代码。 – 2011-05-01 23:40:03

回答

37

我的想法是使用string.chomp

返回一个新的字符串,从str的末尾删除给定的记录分隔符(如果存在)。

这是做你想做的吗?

def remove_trailing_comma(str) 
    str.nil? ? nil : str.chomp(",") 
end 
+0

很干净,优雅。谢谢 – AnApprentice 2011-04-30 18:01:41

+4

如果(str)'将它写成'str.chomp(',')会更优雅。 – 2011-04-30 21:42:30

2

你可以做这样的事情:

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

感谢不错,但nils打破了“私人方法'子'呼吁无:NilClass” – AnApprentice 2011-04-30 17:55:50

+1

是的,我意识到并更新了代码。它现在应该工作。事实上,chomp方法可能更好: str && str.chomp(“,”) – robbrit 2011-04-30 17:58:05

+0

这很好用。谢谢 – AnApprentice 2011-04-30 17:59:01

4

使用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 
+0

如何处理nils?私有方法'chomp'调用nil:NilClass): – AnApprentice 2011-04-30 17:57:41

+0

任何理由更喜欢'str.is_a?(String)'到'str.respond_to?(:chomp)'这样的东西? – 2016-08-08 17:32:55