问题
I have this statement:
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.
回答1:
Yes.
CONST = %w(, - &).freeze
string_tokens[-1].end_with?(*CONST)
Usage:
'test,'.end_with?(*CONST)
#=> true
'test&'.end_with?(*CONST)
#=> true
'test-'.end_with?(*CONST)
#=> true
You use *
(splat operator) to pass multiple args to the String#end_with?, because it accepts multiple.
回答2:
You could also use a regex :
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
回答3:
str = 'hello-'
',-&'.include? str[-1]
#=> true
',$&'.include? str[-1]
#=> false
来源:https://stackoverflow.com/questions/42537226/how-to-see-if-a-string-ends-with-one-of-multiple-characters