Home > OS >  How to check if a string begins with prefix and contains specific keyword in Ruby
How to check if a string begins with prefix and contains specific keyword in Ruby

Time:12-28

I am trying to find an efficient way of doing this. A function to return True if the entry string has a Ph.D/Medical Doctor ( which means prefix of 'Dr.') and the entry has name 'Alex' in it.

I tried the below code which works, but I think there should be a more efficient way of doing it. I will appreciate any thoughts.

str1 = "Dr. Moses Alex"
str2 = "Dr. Ben Mora"

def match st
  if st.include?('Dr.') and st.include?('Alex')
    return true
  else 
   return false
 end
end

match(str1) # true
match(str2) # false

CodePudding user response:

Your code could be simplified to:

def match(string)
  string.start_with?('Dr.') && string.include?('Alex')  
end

This works because a method in Ruby always implicitly returns the value returned by the last statement. Therefore there is no need for explicit returns.

CodePudding user response:

The code looks good. The only feedback I have is regarding the use of 'include?' function for the prefix. Try to use 'start_with?' function instead, so that you don't get True even when the the "Dr" is within the string.

def match st
  if st.start_with?('Dr.') and st.include?('Alex')  
    return true
  else 
    return false
  end
end

CodePudding user response:

I would use String#match? with a simple regular expression:

r = /\ADr\.. \bAlex\b/
"Dr. J. Alex Knowitall".match?(r) #=> true
"He's Dr. J. Alex Knowitall".match?(r) #=> false
"Dr. J. Alexander Knowitall".match?(r) #=> false

We can write the regular expression in free-spacing mode to make it self-documenting:

r =
/
\A    # match beginning of string
Dr\.  # match literal "Dr."
.     # match one or more characters, as many as
      # possible, other than line terminators
\b    # match a word boundary
Alex  # match literal "Alex"
\b    # match a word boundary
/x    # assert free-spacing regex definition mode

With any solution some strings, if permitted, may cause problems, an example being, "Dr. Bubba Knowitall and Alex are brothers".

  • Related