Ruby字符串到原始二进制

in PHP there is the hash() function that can return raw binary data.

http://de2.php.net/manual/en/function.hash.php

I want to do the same in Ruby. How do I do that?

I generate the hash with:

h = Digest::SHA2.new(512) << "hashme"

PHP generates 32 byte of "raw binary output".

If you need the output to be a length of 32, you just need to call Digest::SHA2.new with a bit length of 256 (which is the default):

irb> require 'digest/sha2'
=> true
irb> h = Digest::SHA2.new(256) << "hashme"
=> #<Digest::SHA2:256 02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86>
irb> puts h.length
32
=> nil
irb> puts h
02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86
=> nil

Or just:

irb> h = Digest::SHA2.new << "hashme"
=> #<Digest::SHA2:256 02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86>
irb> puts h.length
32
=> nil
irb> puts h
02208b9403a87df9f4ed6b2ee2657efaa589026b4cce9accc8e8a5bf3d693c86
=> nil

Hope this helps!