如何查看字符串是否以多个字符之一结尾
How to see if a string ends with one of multiple characters
我有这个声明:
string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")
我想把所有的token(","
,"-"
,"&"
)都变成一个常量,简化上面的问题,"does the string end with any of these characters",但是我我不知道该怎么做。
是的。
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 运算符)将多个参数传递给 String#end_with?
,因为它接受多个参数。
您也可以使用正则表达式:
chars = %w(, - &)
ENDS_WITH_CHAR = Regexp.new("["+chars.map{|s| Regexp.escape(s)}.join+']\z')
"abc-" =~ ENDS_WITH_CHAR
# or with Ruby 2.4
"abc-".match? ENDS_WITH_CHAR
str = 'hello-'
',-&'.include? str[-1]
#=> true
',$&'.include? str[-1]
#=> false
我有这个声明:
string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")
我想把所有的token(","
,"-"
,"&"
)都变成一个常量,简化上面的问题,"does the string end with any of these characters",但是我我不知道该怎么做。
是的。
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 运算符)将多个参数传递给 String#end_with?
,因为它接受多个参数。
您也可以使用正则表达式:
chars = %w(, - &)
ENDS_WITH_CHAR = Regexp.new("["+chars.map{|s| Regexp.escape(s)}.join+']\z')
"abc-" =~ ENDS_WITH_CHAR
# or with Ruby 2.4
"abc-".match? ENDS_WITH_CHAR
str = 'hello-'
',-&'.include? str[-1]
#=> true
',$&'.include? str[-1]
#=> false