-1

Is it possible to avoid messing with duplicate array elements when you're messing with the first one?

Consider the following:

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

This is just a Ceaser Cypher fixed at 13 letters over. Straightforward until we hit the duplicate "a"s, which turns into duplicate "n"s after the code runs. As it is here, the upcase! loop upcases in letters everything that was at those indexes in the original string, and I only need those indexes to be capitalized. How do I isolate that?

Andrea McKenzie
  • 239
  • 1
  • 12

3 Answers3

0

Your question was a little unclear. This is my solution from what I got from it.

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

This will return ["N", "A", "q", "e", "r", "n"]

JonahR
  • 94
  • 12
0

Another way you could do this

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"]
Nabeel
  • 2,272
  • 1
  • 11
  • 14
0

For this particular problem, something much simpler will do the trick:

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!"
PJSCopeland
  • 2,818
  • 1
  • 26
  • 40