Un-escaping hexadecimal code


#1

Hi, I receive a String allowing hexadecimal escaping by using %XX
syntax:

%61lice => alice ( %61 == a )

I would like to un-escape the string. I’ve got it using “eval” but I’d
prefer
avoiding using “eval”:

string = “%61lice”
string = eval %{ “#{ string.gsub(/%/,’\x’) }” }
=> “alice”

How could I avoid the usage of “eval” to un-escape the string?

Thanks a lot.


#2

El Viernes, 20 de Febrero de 2009, Iñaki Baz C. escribió:

How could I avoid the usage of “eval” to un-escape the string?

Ops, it is easier than above. CGI lib already does it:

require ‘cgi’
CGI.unescape("%61lice")
=> “alice”

:slight_smile:


#3

Iñaki Baz C. wrote:

string = “%61lice”
string = eval %{ “#{ string.gsub(/%/,’\x’) }” }
=> “alice”

How could I avoid the usage of “eval” to un-escape the string?

s.gsub! /%(\d+)/ do |match|
$1.to_i(16).chr
end
puts s

You might also consider supporting escaped % literals.


#4

El Viernes, 20 de Febrero de 2009, Jeff S. escribió:

puts s

You might also consider supporting escaped % literals.

It fails since it should be:

s.gsub! /%(\d\d)/ do |match|
$1.to_i(16).chr
end

Without this change it would fail when matching:

“%61123”

But fixing it then it works well, thanks a lot :slight_smile:


#5

Iñaki Baz C. wrote:

puts s

You might also consider supporting escaped % literals.

Also, it should consider not just number but A-F

Right you are.


#6

El Viernes, 20 de Febrero de 2009, Jeff S. escribió:

puts s

You might also consider supporting escaped % literals.

Also, it should consider not just number but A-F


#7

Iñaki Baz C. wrote:

El Viernes, 20 de Febrero de 2009, Jeff S. escribió:

puts s

You might also consider supporting escaped % literals.

Also, it should consider not just number but A-F

s = “%4Flice”
s.gsub! /%([\da-fA-F][\da-fA-F])/ { $1.to_i(16).chr }
puts s


#8

Igor P. wrote:

Iñaki Baz C. wrote:

El Viernes, 20 de Febrero de 2009, Jeff S. escribió:

puts s

You might also consider supporting escaped % literals.
Also, it should consider not just number but A-F

s = “%4Flice”
s.gsub! /%([\da-fA-F][\da-fA-F])/ { $1.to_i(16).chr }
puts s

SyntaxError: compile error
(irb):2: syntax error, unexpected ‘{’, expecting $end
s.gsub! /%([\da-fA-F][\da-fA-F])/ { $1.to_i(16).chr }
^


#9

Jeff S. wrote:

SyntaxError: compile error
(irb):2: syntax error, unexpected ‘{’, expecting $end
s.gsub! /%([\da-fA-F][\da-fA-F])/ { $1.to_i(16).chr }
^

Sorry, in Ruby 1.9 this is no longer a Syntax Error