Saturday, 3 September 2011

%:str:

Today, I was fiddling around with Ruby, as I often do.
I produced this abomination:

def wh*t
  p(%w(%s)[0]%t[0]+%:es:)
end
wh"y"

This code works (at least under 1.9.2) and it prints "yes". Bonus points if you can explain wh"y".

Okay, it's not that hard*, but I made an accidental discovery. Aside from ", ' and <<NAME there's yet another way to write out string literals.

Handy to know.

*p - function call, one of the three basic print operations. %w(a b c) produces an array of strings, a quick way to write out lists of strings. "%s" is a format string that is substituted by another string. %w(%s)[0] basically returns "%s". The % operator on a string is the same as a call to format(str, *args). The argument to format here is t[0]. t is the "rest" argument of the method, so it's an array. We call the method with the parameter "y", which makes t equal ["y"]. + concatenates two strings. %:es: is a string literal, "es". Concatenating "y" with "es" gives us... "yes".

No comments: