Question

I found the following ruby code. It translate from a-z to b-za.

Q1. What is za?

Q2. Are zb, zc etc. the next?

Q3. Is there zz? If it is, then what is after zz?

while s = gets
  until s =~ /that|the|this/
    s.tr!('a-z', 'b-za')
  end
  puts s
end
Was it helpful?

Solution

String#tr allows c1-c2 as a shorthand notation for a range of characters:

  • a-z expands to abcdefghijklmnopqrstuvwxyz
  • b-z expands to bcdefghijklmnopqrstuvwxyz
  • b-za is b-z followed by a single a, i.e. bcdefghijklmnopqrstuvwxyza

Finally s.tr!('a-z', 'b-za') replaces each letter by the next one in the alphabet using this mapping:

from_str: abcdefghijklmnopqrstuvwxyz
to_str:   bcdefghijklmnopqrstuvwxyza

OTHER TIPS

It is not b-(za), it is (b-z)a.'a-d' is just a shortcut for 'abcd'.

tr method (and tr!) takes two strings and substitute each occurrence of the each letter in first string with the letter in a second string from the same position (or last letter if second string is shorter). So:

'abcdef'.tr('a-d','*')   #=> '****ef'

Now the string 'a-z' is a shortcut for any letter (down-cased), and you are substituing it with 'b-za' which is shortcut for 'bcdef...xyza' so:

'abcdefz'.tr('a-z', 'b-za') #=> 'bcdefga'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top