[Solved] Convert character ‘A’ to ‘B’ if I add 1 [closed]


Furthering Sergio’s answer, you can isolate the letter-ordinals and use modulo.

class String
  def plus n
    case self
    when ('a'..'z')
      (((ord - 97 + n) % 26) + 97).chr            #ord means self.ord
    when ('A'..'Z')
      (((ord - 65 + n) % 26) + 65).chr
    else
      raise "single-letters only"
    end
  end
end

'a'.plus 2 #=> 'c'
'z'.plus 1 #=> 'a'
'A'.plus 0 #=> 'A'
'Z'.plus 9 #=> 'I'
"https://stackoverflow.com/".plus 1 #=> test.rb:9:in `plus': single-letters only (RuntimeError)

Your question is unclear, but as alluded to in the comments by Stefan, you may want 'A' + 1 #=> 'B' notation. Ruby does allow an overwrite of String#+. But don’t do this, this is just to show you that you can:

class String
  def +(n)
   #code as above...
  end
end

then via syntactic sugar, you can do:

'a' + 2 #=> 'c'
'z' + 1 #=> 'a'
'A' + 0 #=> 'A'
'Z' + 9 #=> 'I'
"https://stackoverflow.com/" + 1 #=> test.rb:9:in `plus': single-letters only (RuntimeError)

2

solved Convert character ‘A’ to ‘B’ if I add 1 [closed]