views:

227

answers:

4

I have a simple byte array

["\x01\x01\x04\x00"]

I'm not sure how I can alter just the second value in the string (I know the array only has one item), whilst still keeping the object a byte array.

Something along these lines:

["\x01#{ARGV[0]}\x04\x00"]
+2  A: 

use each_byte string method:

$ irb --simple-prompt
>> str = "\x01\x01\x04\x00"
=> "\001\001\004\000"
>> str.each_byte {|byte| puts byte}
1
1
4
0
=> "\001\001\004\000"
>>
Eimantas
no wait... I don't think I was as clear as I could have been, I just want to replace the second value, it's all part of a byte array, so it will be output as bytes anyhow... perhaps I'm just way off... you may have the perfect answer though. +1
Joseph Silvashy
@jpsilvashy: Would be good if you add the above info into the question. The original one is kinda vague.
o.k.w
ok, made some changes to my original, thanks @o.k.w. +1
Joseph Silvashy
A: 

I tried this:

led = "%02x" % ARGV[0]

leader = "\x01" + led + "\x04\x00"

leader.each_byte {|byte| puts byte}

but I get:

1 
48
99
4
0

I also tried:

"\x01#{led}\x04\x00"

But I get the same results, I have a feeling that this is really simple I'm just missing the obvious... It seems that I don't know how to deal with bytes.

Joseph Silvashy
+2  A: 

I think the secret is that you have a nested array:

irb(main):002:0> x = ["\x01\x02\x01\x01"]
=> ["\001\002\001\001"]

You can index it:

irb(main):003:0> x[0][1]
=> 2

You can assign into it:

irb(main):004:0> x[0][1] = "\x05"
=> "\005"

And it looks like what you want:

irb(main):005:0> x
=> ["\001\005\001\001"]
Brent.Longborough
Wow, thanks Brent, this works vary well, thanks for the elegant solution to my simple little problem.
Joseph Silvashy
+1  A: 

It might be less confusing to get rid of the array wrapper.

a = ["\x01\x01\x04\x00"]
a = a[0]

a[1] = ...

You can always put the string back inside an array:

a = [a]

Also, technically, it's not a "byte array", it's a single-element Array, with a String object. (And for that matter, strictly speaking, Ruby doesn't really have Array of Type; all Ruby arrays are something like Array of Object elsewhere.)

DigitalRoss
Hey! this is a really great solution also. Makes the string more manageable. Thanks for the insight on Arrays in Ruby as well. +1
Joseph Silvashy