97

How should I check whether a string starts or ends with a given string? There doesn't seem to be any built-in methods available (or maybe it's just the IDE I'm using that isn't having it show up: RDE)

2 Answers 2

182

There are built in methods:

"String".start_with? "S" # true
"String".end_with? "4" # false
Sign up to request clarification or add additional context in comments.

7 Comments

I think they need to give these functions more descriptive names. :)
God bless Matz and Ruby. Although, I think they should be named starts_with? and ends_with?.
@Josh Pinter start_with? is consistent with other functions like eql? and include? - I think of it as a question "Does the string start_with?" rather than a statement "The string starts_with"
Fair enough, but if you think of how you actually use it when writing code, it's exactly like your latter statement, i.e. "The string".starts_with?
@DavidC And for conditionals, you would never say something like "If does the string start with?", you'd say "If the string starts with?".
|
9
string.start_with?("substring")
string.end_with?("substring")

Returns true or false

Source:

http://ruby-doc.org//core-2.2.0/String.html#method-i-start_with-3F

http://ruby-doc.org//core-2.2.0/String.html#method-i-end_with-3F

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.