本文介绍了如何查看字符串是否以多个字符之一结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这句话:
string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")
我想将所有标记(","
,"-"
,"&"
)放入一个常量中,并简化以上内容以询问字符串是否以这些字符中的任何一个结尾",但是我不知道该怎么做.
I would like to put all the tokens (","
, "-"
, "&"
) into a constant and simplify the above to ask, "does the string end with any of these characters", but I'm not sure how to do that.
推荐答案
是.
CONST = %w(, - &).freeze
string_tokens[-1].end_with?(*CONST)
用法:
'test,'.end_with?(*CONST)
#=> true
'test&'.end_with?(*CONST)
#=> true
'test-'.end_with?(*CONST)
#=> true
您使用*
(splat运算符)将多个args传递给 String#end_with?
,因为它接受多个.
You use *
(splat operator) to pass multiple args to the String#end_with?
, because it accepts multiple.
这篇关于如何查看字符串是否以多个字符之一结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!