我有这样的声明:
string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")
我想将所有标记 ( ","
, "-"
, "&"
) 放入一个常量中并简化上面的询问,“字符串是否以这些字符中的任何一个结尾”,但我不知道该怎么做。
是的。
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 operator) 将多个参数传递给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