I'm trying to make a method that, given a string, replaces every letter with its position in the alphabet.
If anything in the text isn't a letter, I want to ignore it and not return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"
(as a string)
I tried this, but it didn't work:
def alphabet_position(text)
alph = ("a".."z").to_a
text = text.split(/./).map {|ch| if ch.in?(alph)
((alph.index[ch]).to_i+1).to_s
else
""
end
}.join(" ").strip
end
Thanks in advance!
question from:
https://stackoverflow.com/questions/65922353/replacing-letters-in-string-with-their-numeric-position-in-the-alphabet-in-ruby 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…