如何查看字符串是否以多个字符之一结尾

2 ruby string ends-with

我有这样的声明:

string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")
Run Code Online (Sandbox Code Playgroud)

我想将所有标记(",""-""&")放入一个常量中,并简化上面的内容来询问“字符串是否以这些字符结尾”,但我不知道该怎么做。

And*_*eko 5

是的。

CONST = %w|, - &|.freeze
string_tokens[-1].end_with?(*CONST)
Run Code Online (Sandbox Code Playgroud)

用法:

'test,'.end_with?(*CONST)
#=> true
'test&'.end_with?(*CONST)
#=> true
'test-'.end_with?(*CONST)
#=> true
Run Code Online (Sandbox Code Playgroud)

您使用*(splat 运算符) 将多个参数传递给String#end_with?,因为它接受多个。