yellowreign
yellowreign

Reputation: 3638

Ruby - Check for String and then Take Substring

I have an attribute that I expect to often begin with "category-".

For example:

@category = "category-ruby-on-rails"

How can I check if @category begins with "category-" and then, if it does, get only the value after "category-" (i.e. "ruby on rails" in this example)?

Upvotes: 0

Views: 59

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

Here are two ways that use a regular expression. (In both, nil is returned if there is no match.)

str = "category-ruby-on-rails"

str[/(?<=\Acategory-).*/]
  #=> "ruby-on-rails"

str[/\Acategory-(.*)/, 1]
  #=> "ruby-on-rails"

(?<=\Acategory-) is a positive lookbehind. It means that "category-" must be matched at the beginning of the string (\A), but it is not part of the match that is returned.

(.*) saves .* into capture group 1. The second argument of the instance method String#[] is the capture group whose contents are to be retrieved and returned by the method.

We could also use String#gsub:

s = str.gsub(/\Acategory-/, '')
  #=> "ruby-on-rails"

but would need to check if there had been a match. For example,

s == str
  #=> false (meaning the match was performed)

There are many other ways to do this, including some that don't use a regular expression.

s = "category-"
str[s.size..-1] if str.start_with?(s)
  #=> "ruby-on-rails"

str = "division-ruby-on-rails"
str[s.size..-1] if str.start_with?(s)
  #=> nil

Upvotes: 3

Othmane El Kesri
Othmane El Kesri

Reputation: 603

You can check if @category starts with "category-" if so you just split your string, drop its first element and join

 result = false
 if @category.start_with?("category-")
    result = @category.split("-").drop(1).join("-")
 end

The "one-line" version :

 result = @category.start_with?("category-") ? @category.split("-").drop(1).join("-") : false

Upvotes: 2

Related Questions