Array problem

Hi,

I need to parse a string char by char, if the char is a number it should go to a array without any modification, however in case of letters they should be decoded into hexadecimals before they go to the array, for example if I have:

text = “hello5” the array should be

=> [“68”, “65”, “6c”, “6c”, “6f”, “5”]

So only letters should be converted.

I wrote the following code but don’t know what the problem with it:

text = “hello5”
number = /\d/
ntext = []

i = 0
while i < text.length
if text[i].chr=~ number
ntext << text[i].chr
else
ntext << text[i].chr.unpack(‘U’)[i].to_s(16)
end
end

It seems to work for the first value only text[0], when replaced with text[1] or anything else I get:
“in `to_s’: wrong number of arguments (1 for 0) (ArgumentError)”

So the array ntext only stores the first converted letter, I couldn’t spot the problem?!!

Your help is really appreciated.

Regards

Hi --

Hi,

I need to parse a string char by char, if the char is a number it should go
to a array without any modification, however in case of letters they should
be decoded into hexadecimals before they go to the array, for example if I
have:

text = "hello5" the array should be

=> ["68", "65", "6c", "6c", "6f", "5"]

So only letters should be converted.

I wrote the following code but don't know what the problem with it:

text = "hello5"
number = /\d/
ntext = []

i = 0
while i < text.length
if text[i].chr=~ number
     ntext << text[i].chr
else
    ntext << text[i].chr.unpack('U')[i].to_s(16)
end
end

One problem with it is that you don't increment i :slight_smile: The other
problem is that you've got unpack('U')[i] but you mean [0].

Keep in mind, though, that you almost never have to maintain a counter
explicitly in Ruby, since the language gives you lots of ways to
operate on collections. For example:

ntext = text.split(//).map {|char|
   case char
   when /\d/
     char
   else
     "%x" % char.unpack('U')
   end
}

David

Hi David,

what is the meaning of "%x" and also ' "%x" % '
Sorry I am so noob.

Thank you

Hi --

Hi David,

what is the meaning of "%x" and also ' "%x" % '
Sorry I am so noob.

It's a way of generating strings, using interpolated arguments. The
target string has %-based format characters, like you'd use with
sprintf. You need to provide one argument for each element in the
format string.

So to print a string and a decimal, you'd do:

   puts "%d is %s" % [10, "ten"] # 10 is ten

%x does a hex conversion:

   puts "%x in hex is %s", [10, "sixteen"] # a in hex is sixteen

David

ntext = text.split(//).map {|char|
   case char
   when /\d/
     char
   else
     "%x" % char.unpack('U')
   end

}

Also as oneliner (1.8 and 1.9)

ntext = text.split(//).map {|char| char =~ /\d/ ? char : "%x" %
char.unpack("U") }