Here are two methods.
# 1 Use String # gsub with regex and then String # upcase and String # []
R = / [az] # match a lower case letter (?=[az]*[AZ]) # match >= 0 lower case letters followed by an upper case letter # in a positive lookahead /x # free-spacing regex definition mode def get_caps(str, n) str.gsub(R,"").upcase[0,4] end get_caps("ThisIsMyString", 4) #=> "TIMS" get_caps("ThisIsOneVeryLongString", 4) #=> "TIOV" get_caps("MyString", 4) #=> "MSTR" get_caps("abcde", 4) #=> "ABCD" get_caps("", 4) #=> "" get_caps("AbcdefGh", 4) #=> "AGH"
# 2 Determine the index of the last capital letter, and then build the line
def get_caps(str, n) idx = str.rindex(/[AZ]/) return str[0,4].upcase if idx.nil? str.each_char.with_index.with_object('') { |(c,i),s| s << c.upcase if (s.size < n && (i > idx || c == c.upcase)) } end get_caps("ThisIsMyString", 4)
If you want to return nil if the returned string contains fewer n characters, add this check to the methods.
source share