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


CONST = %w(, - &).freeze


#=> true
#=> true
#=> 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