I am testing two strings to see if they are equal.
One string is just a simple string: "\17"
The other is parsed to: "\17"
num = 7
num2 = "\17"
parsed_num = "\1#{num}"
puts parsed_num.class
puts num2.class
if parsed_num == num2
puts 'Equal'
else
puts 'Not equal'
end
It returns:
String
String
Not equal
My goal is to have parsed_num exactly the same as the literal num2
I am going to take the opposite answer and assume that “\17” is correct, then consider this code:
Result:
The reason why
"\1#{num}"didn’t work is that string literals — and the embedded escape sequences — are handled during parsing while the string interpolation itself (#{}) happens later, at run-time. (This is required, because who knows what may happen to be innum?)In the case of
p2I usedeval, which parses and then executes the supplied code. The code there is equivalent toeval('"\17"'), becauseparsed_numcontained the 3-letter string:\17. (Please note, this approach is generally considered bad!)In the case of
p3I manually did what the parser does for string interpolation of\octal: took the value ofoctal, in, well, octal, and then converted it into the “character” with the corresponding value.Happy coding.