Ruby's pack and unpack explained

后端 未结 4 600
长发绾君心
长发绾君心 2021-02-08 04:40

Even after reading the standard documentation, I still can\'t understand how Ruby\'s Array#pack and String#unpack exactly work. Here is the example that\'s causing me the most t

4条回答
  •  轮回少年
    2021-02-08 05:02

    The Array#pack method is pretty arcane. Addressing question (2), I was able to get your example to work by doing this:

    > ["61", "62", "63"].pack("H2H2H2")
    => "abc" 
    

    See the Ruby documentation for a similar example. Here is a more general way to do it:

    ["61", "62", "63"].map {|s| [s].pack("H2") }.join
    

    This is probably not the most efficient way to tackle your problem; I suspect there is a better way, but it would help to know what kind of input you are starting out with.

    The #pack method is common to other languages, such as Perl. If Ruby's documentation does not help, you might consult analogous documentation elsewhere.

提交回复
热议问题