user2387766
user2387766

Reputation:

How to use a Regex with the end_with? method in Ruby?

I just learned about regular expressions, and I understand that they're a pattern used to search for a match in a given string.

I understand how using (/[aeiou]/) with the start_with? method works. The regex (/[aeiou]/) is a class of characters that I am checking for in the given string. And more specifically, I am checking to see if the given string starts with any of those characters in the regex.

However, when I try to use the same pattern with the end_with? method, I get a TypeError and it seems that the regex cannot be used.

Why is this? To me, both of these methods seem to share a very similar documentation in the Ruby guides.

enter image description here

Upvotes: 5

Views: 2998

Answers (1)

tadman
tadman

Reputation: 211600

Usually the point of start_with? or end_with? is to provide an alternative to using a regular expression. That is the following are similar in intent:

"example".start_with?("ex")
"example".match?(/\Aex/)

Where if you want to use a regular expression then use match or match? which is available in newer versions of Ruby.

Just convert your regular expression to be anchored:

str.start_with?(/\A[aeiou]/)

Upvotes: 6

Related Questions