Search code examples
rubyintegerhexpackfixnum

Ruby: using pack("n") with integers


I know that I need to use [5].pack("n") for example. This produces the output "\x00\x05"

But now I want to pack the length of a string. If I use:

"Hello".length.pack("n")

I get the error

undefined method `pack' for 5:Fixnum (NoMethodError).

How can I fix this? I've already tried to convert "Hello".length into an integer with "Hello".length.to_i but then I get the same error. Is there any way to fix this?


Solution

  • You need to use an array, not integer("Hello".length is already one).

    ["Hello".length].pack("n")
    # => "\x00\x05"