Search code examples
rubystringcapitalization

How to count words in array that start with a capital letter


I'm working on an array containing Twitter handles such as:

array = ["@user1","@User2","@uSer3","@User4"]

I want to know how many handles start with a capital letter.


Solution

  • I used a regex to match @ followed by a capital letter at the start of the string.

    count is the most semantic function (thanks to @crenmo):

    array.count {|e| e =~ /^@[A-Z]/}
    

    select is useful if you'd like a list of matched elements:

    array.select {|e| e =~ /^@[A-Z]/ }
    

    Use [[:upper:]] instead of [A-Z] if you wish to match non-English uppercase letters (thanks to @CarySwoveland).

    For reference, indexing into a string can be done with bracket notation (although I didn't wind up using this): str[0]