Home > Software engineering >  Ruby: Get the value if end_with? is true
Ruby: Get the value if end_with? is true

Time:07-07

Looking for a clean way to return the characters of a string if end_with? evaluates to true. i.e.

s = "my_name"
name = s.end_with?("name")

puts name
>> "name"

My use case would look somewhat like this:

file_name = "some_pdf"

permitted_file_types = %w(image pdf)

file_type = file_name.end_with?(*permitted_file_types)

puts file_type
>> "pdf"

CodePudding user response:

I would do this:

"my_name".scan(/name\z/)[0]
#=> "name"

"something".scan(/name\z/)[0]
#=> nil

CodePudding user response:

May be using match and \z (end of string)?

string = "my_name"

suffix1 = "name"
suffix2 = "name2"

In Ruby >= 3.1

result1 = %r{#{suffix1}\z}.match(string)&.match(0)
# => "name"

result2 = %r{#{suffix2}\z}.match(string)&.match(0)
# => nil

In Ruby < 3.1

result1 = %r{#{suffix1}\z}.match(string)&.[](0)
# => "name"

result2 = %r{#{suffix2}\z}.match(string)&.[](0)
# => nil

Just for fun trick with tap:

string.tap { |s| break s.end_with?(suffix1) ? suffix1 : nil }
# => "name"

string.tap { |s| break s.end_with?(suffix2) ? suffix2 : nil }
# => nil

CodePudding user response:

ruby already has a String#end_with? method, going back to at least version 2.7.1, maybe earlier. But it returns a boolean and you want the matched string to be returned. You're calling a method on an instance of String, so you're apparently wanting to add a method to the String class.

class String #yeah we're monkey patching!
  def ends_with?(str) #don't use end_with.. it's already defined
    return str if self.end_with?(str)
  end
end

#now 
s="my_name"
s.ends_with?("name") #=> "name"

But I really wouldn't bother with all that... I'd just work with what Ruby provides:

s = "my_name"
str = "name"
result = str if s.end_with?(str)
  • Related