Member-only story

Find the first non-repeated character in a String in ruby

Gokul
1 min readMar 14, 2021

--

This is the most frequently asked ruby interview question for the entry-level engineer.

There are many ways to find the first non-repeated character in the ruby with the help of a few inbuilt methods we can achieve this easily.

Method 1

def first_non_repeated_character(input)
output = ''
input.chars do |c|
input.count(c) == 1 ? (output = c; break) : output = ''
end
output
end

output

input = 'This is the example of first non-repeated character'.downcaseputs first_non_repeated_character(input) #=> x

Method 2

def first_non_repeated_character(input)
input.chars.find { |character| input.count(character) == 1 }
end

output

input = 'This is the example of first non-repeated character'.downcaseputs first_non_repeated_character(input) #=> x

Method 3

def first_non_repeated_character(input)
input.chars.detect { |character| input.count(character) == 1 }
end

output

input = 'This is the example of first non-repeated character'.downcaseputs first_non_repeated_character(input) #=> x

Thank you for reading my post. If you like it show your support with claps 👏.

Happy coding!!!

--

--

Gokul
Gokul

No responses yet