Easy ROT13 Ruby "programme" mystery -
i made simple rot13 programme , don't understand 1 thing:
a = 'abcdefghijklmnopqrstuvwxyz' (a.length+1).times |i| print a[i + 13] if i>13 print a[i %14] end end
outputs:
nopqrstuvwxyzabcdefghijklm
if don't add +1
after a.length
, iteration ends letter l
. however, if use print a[i]
inside iteration, starts a
, ends z
no +1
addition needed.
can explain mystery me?
as may know, .times
loop invokes block specified number of times, passing each iteration incremented value.
if 26.times {|i| puts i}
print values 0 25. to, not including last value.
now let's walk through loop. @ first iteration, i
0. print 14th character of string, "n"
(at index 13, zero-based). don't go condition because 0 not greater 13. on second iteration print 15th character, "o"
. , keep doing this, until reach i=14
.
at point, "magic" begins. first, attempt print 27th character of string. there's no such character print literally nothing. condition triggered , go in.
i % 14
equals 0, print zeroth character, "a"
. next iteration print character @ index 1 (15 % 14
) , on, until .times
finishes iteration , stops calling block. now, logic work, last value i
must 26, 12 in i % 14
, print "m"
.
length of entire string 26. remember, .times
counts not including number? that's why add 1 length, counts 0 26. that's mystery.
there many-many ways of improving code, , you'll learn them in time. :)
update
i knew looked odd code. and, of course, there's bug. when i
13 don't print first time and don't go condition. waste 1 iteration. classic example of "off 1" class of errors. here's fixed version of code doesn't waste iterations , contains no mysteries:
a.length.times |i| print a[i + 13] if > 12 print a[i % 13] end end
Comments
Post a Comment