1

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • What is `string_tokens`? We can assume a string, but for clarity it needs to be defined. When asking for help, we need to see working code showing what you tried. That helps us see any errors you're making and lets us fix/respond with answers that directly apply to your use. Please see "[ask]" and the linked pages and "[mcve](https://stackoverflow.com/help/minimal-reproducible-example)" – the Tin Man Oct 17 '19 at 20:08

3 Answers3

4

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
0

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
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0
str = 'hello-'

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

',$&'.include? str[-1]
  #=> false
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100