0

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"]

3 Answers 3

4

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks Brent, this works vary well, thanks for the elegant solution to my simple little problem.
2

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"
>>

2 Comments

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
@jpsilvashy: Would be good if you add the above info into the question. The original one is kinda vague.
1

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.)

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.