1

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)}
  end
end

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

1
  • I'll try to explain the method in as plain English as I can. (0...self.length/2) returns a number that is half the string's length. (self is a keyword that means, in the context of a method like to_bytes, the string upon which to_bytes is being requested.) map takes the number (half the string's length), takes two characters from the string at a time, and converts each pair to hex, and places the result in an array. Commented Oct 10, 2011 at 13:20

2 Answers 2

2

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

1 Comment

I see, this things does pretty much nothing at all, but when I look at the "a".to_bytes and some other examples, the to_bytes ruins the whole input... still wondering why would somebody do that, cause I am modifying code of someone else, but thanks for your time, I appreciate it.
-1

Seems like much to do about nothing...

Why don't you just

"My string".bytes.reverse
# Or
def reverse_bytes(str)
    str.bytes.reverse
end

Comments

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.