Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the first non-recurring letter of a string in Ruby?

Tags:

string

ruby

I have a string "teststring". I want to find first non-recurring character in Ruby.

I have this Python code:

def first_non_repeat_character(teststring)
    unique=[]
    repeated=[]
    for character in teststring:
        if character in unique:
            unique.remove(character)
            repeated.append(character)
        else:
            if not character in repeated:
                unique.append(character)
    if len(unique):
        return unique[0]
    else: 
        return false
like image 258
vidal Avatar asked Oct 20 '25 11:10

vidal


1 Answers

def first_non_repeat_character(string)
  string.chars.find { |character| string.count(character) == 1 }
end

first_non_repeat_character('teststring') # => "e"
like image 153
ndnenkov Avatar answered Oct 23 '25 00:10

ndnenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!