Rotating letters in a string so that each letter is shifted to another letter by n places

前端 未结 4 1578
無奈伤痛
無奈伤痛 2021-01-05 20:07

I have been tasked with coming up with a way of encoding a string. Among other things, I need to shift each letter by a given number but the transformed letter must be a let

4条回答
  •  灰色年华
    2021-01-05 21:00

    Arrays have a rotate method:

    def play_pass(str,n)
      abc = ("a".."z").to_a.join
      abc_rot = abc.chars.rotate(n).join
      str.tr(abc, abc_rot)
    end
    
    p play_pass("abcdefghijklmnopqrstuvwxyz", 2)
    # => "cdefghijklmnopqrstuvwxyzab"
    

    A negative n rotates the other way.

提交回复
热议问题