Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby inbuilt method to get the position of letter in the alphabet series?

Tags:

ruby

Input: str = "stackoverflow"

Output: [19 20 1 3 11 15 22 5 18 6 12 15 23]

Do we have any method to get the position of the letters in ruby?

So that I can use something like str.chars.map { |al| al.some_method }.

str.chars = ["s", "t", "a", "c", "k", "o", "v", "e", "r", "f", "l", "o", "w"]

like image 887
vikas95prasad Avatar asked Dec 13 '25 08:12

vikas95prasad


1 Answers

You can do this. I'd use String#chars which returns the ASCII numbers of each character in the string.

'abcdggg'.bytes
# => [97, 98, 99, 100, 103, 103, 103] 

As you can see, the alphabet is sequential, each letter is one higher than the previous one. You can get it's position in the alphabet by taking 96 from the number.

Note that the upper-case letter is in a different position, but we can fix this using String#downcase.

To get all the alphabetical positions in a string (if it only has letters) we can write this method.

def alphabet_positions(string)
  string.downcase.bytes.map{|b| b - 96}
end

This will work unexpectedly if any characters aren't letters, tho.

like image 56
AJFaraday Avatar answered Dec 16 '25 17:12

AJFaraday



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!