Determine if a string has all the same characters

func analyze_string(str) {
    var chars = str.chars
    chars.range.to_a.each_cons(2, {|a,b|
        chars[a] == chars[b] || return b
    })
    return str.len
}

var strings = ["", "   ", "2", "333", ".55", "tttTTT", "4444   444k", "pรฉpรฉ", "๐Ÿถ๐Ÿถ๐Ÿบ๐Ÿถ", "๐ŸŽ„๐ŸŽ„๐ŸŽ„๐ŸŽ„"]

strings.each {|str|
    print "'#{str}' (size #{str.len}): "
    var idx = analyze_string(str)

    if (idx == str.len) {
        say "all the same."
    }
    else {
        say "first different char '#{str[idx]}' (#{'%#x' % str[idx].ord}) at position #{idx}."
    }
}

Output:

Last updated

Was this helpful?