【发布时间】:2021-05-01 11:26:48
【问题描述】:
我正在尝试创建一个方法,给定一个字符串,用它在字母表中的位置替换每个字母。
如果文本中的任何内容不是字母,我想忽略它而不返回它。
"a" = 1, "b" = 2, etc.
例子
alphabet_position("The sunset sets at twelve o' clock.")
应该返回"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"(作为字符串)
我试过了,但没有用:
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
提前致谢!
【问题讨论】:
标签: ruby string indexing methods replace