如何查看字符串是否以多个字符之一结尾 [英] How to see if a string ends with one of multiple characters

查看:121
本文介绍了如何查看字符串是否以多个字符之一结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这句话:

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.

推荐答案

是.

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运算符)将多个args传递给

You use * (splat operator) to pass multiple args to the String#end_with?, because it accepts multiple.

这篇关于如何查看字符串是否以多个字符之一结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆