1

我有这样的声明:

string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")

我想将所有标记 ( ",", "-", "&") 放入一个常量中并简化上面的询问,“字符串是否以这些字符中的任何一个结尾”,但我不知道该怎么做。

4

3 回答 3

4

是的。

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?,因为它接受多个。

于 2017-03-01T16:41:14.953 回答
0

您还可以使用正则表达式:

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
于 2017-03-01T18:11:34.453 回答
0
str = 'hello-'

',-&'.include? str[-1]
  #=> true

',$&'.include? str[-1]
  #=> false
于 2017-03-02T07:13:09.650 回答