Ruby 2.7 adds Symbol#start_with? and Symbol#end_with? methods

Ruby 2.7 has added new methods Symbol#start_with? and Symbol#end_with?

These methods behave similar to the methods with same name in String class.

Symbol#start_with?

The Symbol#start_with? returns true if the symbol starts with provided prefixes. The provided prefixes can be a string, regex or multiple strings. In case of multiple strings it returns true if any of string is prefix of symbol.

:saeloun.start_with?("sae")
=> true
:saeloun.start_with?("new")
=> false
:saeloun.start_with?("sae", "new")
=> true
:saeloun.start_with?("means", "new")
=> false
:saeloun.start_with?(/SA/i)
=> true
:saeloun.start_with?(/s./)
=> true
:saeloun.start_with?(/ne*/)
=> false

Symbol#end_with?

Similarly Symbol#end_with? returns true if the symbol ends with provided suffixes. Again the provided suffix arguments can be a string, multiple strings.

:saeloun.end_with?("oun")
=> true
:saeloun.end_with?("new")
=> false
:saeloun.end_with?("oun", "new")
=> true
:saeloun.end_with?("means", "new")
=> false
:saeloun.end_with?(/.n/)
=> TypeError (no implicit conversion of Regexp into String)

A key thing to note here is, as we can see the start_with? method accepts regex as arguments, while the end_with? method doesn’t accept regex arguments.

Need help on your Ruby on Rails or React project?

Join Our Newsletter