-1

当您弄乱第一个数组元素时,是否可以避免弄乱重复的数组元素?

考虑以下:

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。直截了当,直到我们点击了重复的 s,在代码运行后"a"它变成了重复的 s。"n"就像这里一样,原始字符串中那些索引处upcase!的所有内容中的循环都大写letters,我只需要将这些索引大写。我如何隔离它?

4

3 回答 3

0

你的问题有点不清楚。这是我从中得到的解决方案。

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"]

于 2016-02-18T01:05:46.600 回答
0

你可以这样做的另一种方法

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"]
于 2016-02-18T01:16:26.500 回答
0

对于这个特殊的问题,一些更简单的方法可以解决问题:

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!"
于 2016-02-18T01:19:14.853 回答