Editing Topic: RCR150 Project: RCR | RCRchive home

RCR 150: String#start_with? / #end_with?

submitted by anonymous on 2003-08-21 10:56:56


This is a legacy RCR. If this is your RCR, please resubmit it using the new format and process.


I'd like the following to be in Standard Ruby:

class String
  def start_with?(other, length = other.length)
    self[0...length] == other[0...length]
  end

  def end_with?(other, length = other.length)
    self[-length..-1] == other[-length..-1]
  end
end

This allows the more readable "foobar".start_with? "foo" and "barqux".end_with? "qux" instead of the more long winded and error prone "foobar"[0...3] == "foo" and "barqux"[-3..-1] == "qux" .

IMHO checking whether a String starts or ends with another String is done commonly so there should be a simple and clear way to do so.



Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog