Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

Replacing letters in string with their numeric position in the alphabet in ruby

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
    def alphabet_position(text)
      text.downcase.split('').map do |letter|
        index = ('a'..'z').find_index(letter)
        index + 1 if index
      end.compact.join(' ')
    end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...