Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a method that checks if a string starts with a capitalized letter?

Tags:

ruby

So far I have:

def capitalized?(str)
  str[0] == str[0].upcase
end

THe problem wit this is that it returns true for strings like "12345", "£$%^&" and"9ball" etc. I would like it to only return true if the first character is a capital letter.

like image 712
Steve Avatar asked Mar 04 '23 05:03

Steve


1 Answers

You can use match? to return true if the first character is a letter in the range of A to Z both uppercase or not:

def capitalized?(str)
  str.match?(/\A[A-Z]/)
end

p capitalized?("12345") # false
p capitalized?("fooo")  # false
p capitalized?("Fooo")  # true

Also you can pass a regular expression to start_with?:

p 'Foo'.start_with?(/[A-Z]/) # true
p 'foo'.start_with?(/[A-Z]/) # false
like image 159
Sebastian Palma Avatar answered Mar 08 '23 23:03

Sebastian Palma