当你弄乱第一个数组元素时,是否有可能避免弄乱重复的数组元素?
请考虑以下事项:
def rot13(str)
alphabet = ("a".."z").to_a
letters = str.split("").each{|x| x.downcase! }
letters.map! do |let|
alphabet[(alphabet.index(let) + 13) % alphabet.length]
end
#werd = letters.join("")
letters.map.with_index do |char,index|
str.each_char.with_index do |c,idx|
if str[idx].upcase! == nil
letters.at(idx).upcase!
end
end
end
#werd
letters
end
rot13("ANdrea")
这只是一个固定在13个字母以上的Ceaser Cypher。很简单,直到我们达到重复的"a"
s,在代码运行后变成重复的"n"
s。就像这里一样,upcase!
循环letters
原始字符串中这些索引中的所有内容,我只需要将这些索引大写。如何隔离它?
另一种方法可以做到这一点
def input(str)
alphabet = ("a".."z").to_a
str.chars.map do |let|
next let unless alphabet.include?(let.downcase)
ceaser_letter = alphabet[(alphabet.index(let.downcase) + 13) % alphabet.length]
let == let.upcase ? ceaser_letter.upcase : ceaser_letter.downcase
end
end
input('ANdrea')
=> ["N", "A", "q", "e", "r", "n"]
你的问题有点不清楚。这是我从中得到的解决方案。
def rot13(str)
alphabet = ("a".."z").to_a
cap_alphabet = ("A".."Z").to_a
letters = str.split("")
letters.map! do |letter|
if alphabet.include?(letter)
# Change these for different scambling
alphabet[(alphabet.index(letter) + 13) % alphabet.length]
else
cap_alphabet[(cap_alphabet.index(letter) + 13) % alphabet.length]
end
end
end
p rot13("Andrea")
这将返回 ["N", "A", "q", "e", ">r", "n"]
对于这个特定的问题,更简单的东西就可以了:
def rot13(str)
str.chars.map do |c|
next c unless c =~ /[A-z]/
((c.ord % 32 + 13) % 26 + c.ord / 32 * 32).chr
end.join
end
rot13("It's PJSCopeland!")
#=> "Vg'f CWFPbcrynaq!"