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)}
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
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
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
精彩评论