Natalia Natalia -4 years ago 122
Ruby Question

Is there a simpler ask if a string ends with one of multiple characters?

I'm using Ruby 2.4. I hvae 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 some kind of constant and somehow simplify the above to ask, does the string end with any of these characters, but I'm not sure how to do that. Any ideas?

Answer Source

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 :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download