0

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)?

1
  • You could check, will they always be some-words-separated-by-hyphen? no matter if this starts with category-? Commented Jun 10, 2017 at 21:29

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

It seems that you can solve everything with regexp. Nice!
2

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

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.