Strings are not equal

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

On Wed, Nov 9, 2011 at 20:16, Mike S. [email protected]
wrote:

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”

You might think so, but nope:

“\17”
=> “\u000F”
“\1#{7}”
=> “\u00017”
“\001”
=> “\u0001”
“\01”
=> “\u0001”
“\1”
=> “\u0001”
=> “\0017”
“\u00017”

The \ causes things to be escaped, with the subsequent 3 digits being an
octal number. “\001” == “\01” == “\1”, and “\1#{7}” == “\1” + “#{7}” ==
“\001” + “#{7}”

To see the octal base:

“\001\005\1\01\010\060”.bytes.to_a
=> [1, 5, 1, 1, 8, 48]

since, for example, 6*8^1 = 48. And since it expects numbers 0-7, 8
breaks
you out of it:

“\08”
=> “\u00008”

In other words, “\08” == “\008” == “\0008” == “\000” + “8”. Finally,
“\8”
== “8”.

You can extend this to, e.g., “\xFA” for hexadecimal.

Beware the escaping character. :slight_smile:

On Wed, Nov 9, 2011 at 9:27 PM, Adam P. [email protected]
wrote:

Beware the escaping character. :slight_smile:

Trapped by the escaping character - and there is no escape. :wink:

SCNR

robert