Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to write a regex in Ruby that returns true / false

I am trying to write a regex that takes a word and returns true for words starting with a vowel and returns false for words starting with a consonant. I have never written regex before, and I'm a little confused on how to write the expression. This is what I have so far:

def starts_with_a_vowel?(word)
  if word.match(/\A+[aeiou]/) == true
    return true
  else
    return false  
  end
end

Edit: So if word = "boat" , expression should return false. If word = "apple", expression should return true.

like image 427
alexnewby Avatar asked Dec 06 '22 16:12

alexnewby


2 Answers

word.match? /\A[aeiou]/i is literally all you need. (ruby >= 2.4)

It matches the beginning of the string \A followed by a vowel [aeiou] in a case-insensitive manner i returning a bool word.match?

Before ruby 2.4 you have to use word.match and convert it to a bool, which is easiest done by logically negating it twice with !!

like image 180
DarkWiiPlayer Avatar answered Dec 08 '22 05:12

DarkWiiPlayer


EDIT:

OK.. So.. I never tested the code I formerly wrote.. it was meant only as some suggestion how to use the match with regex, but it not worked at all.. (that code snippet is now attached to the end of my answer fyi)

this here should be the working one:

def starts_with_a_vowel?(word)
  !!word.capitalize.match(/\A+[AEIOU]/)
end

..but how it was mentioned by Eric Duminil here below in comments, the method/function is not needed

!!word.capitalize.match(/\A+[AEIOU]/) can be used directly.. it returns true or false

but there are surely other (maybe better) solutions too..

..and here is the NOT working code, which I formerly wrote:

def starts_with_a_vowel?(word)
  return word.match(/\A+[aeiou]/).length > 0
end

..the match method returns nil when not match and because nil has no length method defined, it raises NoMethodError

like image 33
n0rph3u5 Avatar answered Dec 08 '22 04:12

n0rph3u5