-3

I'm studying ruby ​​on rails and I'm seeing a code, but I could not understand how it actually works.

''''ruby

validate: first_letter_must_be_uppercase

private

def first_letter_must_be_uppercase

   errors.add ("name", "first letter must be uppercase") unless name =~ /[A-Z].*/

end

  • 1
    What's the specific question? Regarding regex? I'd recommend reading a regex tutorial/ – Dave Newton Apr 02 '19 at 13:57
  • Possible duplicate of [What do =~ and /\ mean in Ruby?](https://stackoverflow.com/questions/26938262/what-do-and-mean-in-ruby) – Sovalina Apr 02 '19 at 14:55

1 Answers1

1

The code is basically checking that the string should contain the first letter in the upper case using the regular expression

explanation:

/[A-Z].*/
  • [A-Z] - Checks for any capital letter from A to Z
  • . - checks for any wildcard character
  • * - matches for 0 to any number of repetition.

To sum up

The input string should match the following format - A capital letter from A-Z and then should have 0 to any number of wildcard characters

You can check it on Rubular

EDIT

As pointed out by @vasfed if you want to match the first character the regex need to be changed to

/\A[A-Z].*/

\A - Ensure start of the string

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
  • 1
    to be precise - not first, but anywhere in string, regex does not have any anchors, probably it should have been `/\A[A-Z]/` – Vasfed Apr 02 '19 at 15:46