无法弄清楚如何获得基本的ruby'加密器'上班

时间:2017-06-08 02:29:46

标签: ruby

基本上想要制作' abc'进入' bcd'。我在想,如果我在短语的第一个末尾加上下面的字母并删掉原来的第一个字母,最后我得到了最终的解决方案。有点卡住了,希望有人可以为我揭开它。感谢

public interface dbDao<T>{

    public T t; //this is generic class, all class can use this method  

} 

4 个答案:

答案 0 :(得分:3)

您的代码分析.. 由于您已经使用空字符串初始化encrypted_str,因此无需将其附加到原始字符串,然后再将slice添加到它...这就是它变得混乱的地方..只需执行以下操作..

until index == duration #you are not using duration too if assigned it to a variable
  encrypted_str += str[index].next[0]
  index += 1 
end

将索引0作为下一个字符串,因为'z'.next返回aa

另一种衬垫方法是......

message.each_char.map { |s| s.next[0] }.join
  • chars会将邮件拆分为单个字符

  • map将操纵的字符收集到数组中

  • join会将映射数组中的单个字符再次连接到字符串

解密

encrypted_str.each_char.map { |s| s.eql?('a') ? 'z' : (s.ord-1).chr }.join

答案 1 :(得分:2)

ENCRYPT = [*'a'..'z'].zip([*'b'..'z', 'a']).to_h
  #=> {"a"=>"b", "b"=>"c",..., "y"=>"z", "z"=>"a"}
DECRYPT = ENCRYPT.invert
  #=> {"b"=>"a", "c"=>"b",..., "z"=>"y", "a"=>"z"}

def encrypt(str)
  crypt(str, ENCRYPT)
end

def decrypt(str)
  crypt(str, DECRYPT)
end

def crypt(str, mapping)
  str.gsub(/./, mapping)
end

encrypt('abc')   #=> "bcd"
decrypt('bcd')   #=> "abc"

encrypt('amnrz') #=> "bnosa"
decrypt('bnosa') #=> "amnrz"

这使用String#gsub的形式,它将哈希作为参数。另请参阅Hash#invert

答案 2 :(得分:2)

另一种选择,它使用更多的stdlib功能:)

def original
  "abcdefghijklmnopqrstuvwxyz"
end
def replacement 
  "bcdefghijklmnopqrstuvwxyza" 
end

def encrypt(str)
  str.tr(original, replacement)
end

def decrypt(str)
  str.tr(replacement, original)
end


encrypt('abc') # => "bcd"
decrypt('bcd') # => "abc"

也非常灵活(与基于succ的方法相比)。您可以更改replacement字母来定义任意转换规则。

答案 3 :(得分:0)

您可以将字符串中的所有字母作为参数传递,并且&#34;追加&#34;它是它的下一个字符,只返回一个长度等于参数的字符串:

def encrypt(str)
  # str[1..-1]        # Get the string from the second character to the last one.
  # <<                # Add to the "str" argument: 
  # str[-1].next      # the value for the next character using the last one.
  # ()[0..str.size-1] # Take the content inside parenthesis from the first character
                      # up to the element with index equal to the numbers of characters
                      # in the str argument less 1.
 (str[1..-1] << str[-1].next)[0..str.size-1]
end

p encrypt('abc')
# => "bcd"
p encrypt('bcd')
# => "cde"
p encrypt('xyz')
# => "yza"
p encrypt('xyza')
# => "yzab"
p encrypt('xyzab')
# => "yzabc"