How to see if a string ends with one of multiple characters

こ雲淡風輕ζ 提交于 2019-12-11 05:27:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!