Iamvery

The musings of a nerd


Ruby String#end_with?

— Feb 05, 2013

TL;DR Use Ruby’s String#end_with? to check a string for suffixes!

For a recent Rails project, I needed to exclude a number of strings from an array if they ended with any of several difference suffixes. After coming up with a questionable solution, I discovered Ruby’s String#end_with? method! The solution is simple and idiomatic.

    suffixes = %w(abc def ing)
    %w(something abcdef other_things).delete_if do |item|
      item.end_with? *suffixes
    end
    # => ["other_things"]

Notice you have to “splat” the suffixes array. This is because end_with? takes any number of suffixes as arguments rather than an array.

© Jay Hayes