Redrick Redrick - 2 years ago 91
Ruby Question

Ruby to_bytes reverse function needed

I have this function from github or whatever:

class String
def to_bytes
(0...self.length/2).map {|i|self[i*2,2].to_i(16)}

and my point is, that I am not really sure what is the whole thing doing, especially the self[something] part and please can somebody help me to reverse this procedure? I am not experienced and I kind of desperately need to get those numbers back into string.

Thanks a lot

Answer Source

I don't think you can reliably convert the result of to_bytes back to the original string. Both "a".to_bytes and "b".to_bytes will produce [0]. However, assuming that this isn't a problem for you, the reverse of your to_bytes method would be something like this:

def reverse_string_to_bytes bytes
  result = ""
  bytes.each do |pair|
    result << pair.to_s(16)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download