Monday, September 15, 2014

Find a unique character

It never hurts to get a little more practice with solving problems in Ruby. A simple problem that I came across is how to find the first unique element in a string.

This can be done using hashes and counting how many times an element appears in the string.

example = "Hhello, Mr. Doglet."

def find_first_unique(example)
    hsh = Hash.new(0)
    example.downcase.split("").each { |i| hsh[i] +=1 }
    hsh.each { |key, value| return key if value == 1 }
end

puts find_first_unique(example) #=> ,


No comments :

Post a Comment