Home > front end >  Increment alphabetical string in Ruby on rails
Increment alphabetical string in Ruby on rails

Time:05-27

Task I want to solve:

Write a program that takes a string, will perform a transformation and return it. For each of the letters of the parameter string switch it by the next one in alphabetical order. 'z' becomes 'a' and 'Z' becomes 'A'. Case remains unaffected.

def rotone(param_1)
  a = ""
param_1.each_char do |x|
    if x.count("a-zA-Z") > 0
        a << x.succ
    else
        a << x
    end
end
   a
end

And I take this:

Input:  "AkjhZ zLKIJz , 23y "
Expected Return Value: "BlkiA aMLJKa , 23z "
Return Value:          "BlkiAA aaMLJKaa , 23z "

When iterators find 'z' or 'Z' it increment two times z -> aa or Z -> AA

CodePudding user response:

input = "AkjhZ zLKIJz , 23y"

Code

p input.tr('a-yA-YzZ','b-zB-ZaA')

Output

"BlkiA aMLJKa , 23z"

CodePudding user response:

CODE = [*'a'..'y', *'A'..'Y'].each_with_object({}) { |c,h| h[c] = c.next }
  .merge('z'=>'a', 'Z'=>'A')
  .tap { |h| h.default_proc = proc { |_h,k| k } }
  #=> {"a"=>"b", "b"=>"c",..., "y"=>"z", "A"=>"B", "B"=>"C",..., "Y"=>"Z",
  3    "z"=>"a", "Z"=>"A"}
DECODE = CODE.invert.tap { |h| h.default_proc = proc { |_h,k| k } }
  #=> {"b"=>"a", "c"=>"b",..., "z"=>"y", "B"=>"A", "C"=>"B",..., "Z"=>"Y",
  3    "a"=>"z", "A"=>"Z"}

For example,

CODE['e'] #=> "f"
CODE['Z'] #=> "A"
CODE['?'] #=> "?"
DECODE['f'] #=> "e"
DECODE['A'] #=> "Z"
DECODE['?'] #=> "?"

For example,

str = "The secret message is in the hollow of the tree 40m north of the barn"

rts = str.gsub(/./m, CODE)
  #=> "Uif tfdsfu nfttbhf jt jo uif ipmmpx pg uif usff 40n opsui pg uif cbso"
rts.gsub(/./m, DECODE)
  #=> "The secret message is in the hollow of the tree 40m north of the barn"

The regular expression /./ matches every character other than line terminators. Adding the option m (/./m) causes . to match line terminators as well.

See String.next, Hash#merge, Object#tap, Hash#default_proc= and Hash#invert.

An important advantage of using hashes is that key lookups are very fast when compared to a linear search of characters.

  • Related