Method Check: String#sum #
String#sum( n = 16 )
computes an n-bit checksum for a string. This amounts to addition of the character codes for a string. Proof: ?R + ?H <redpre#0> “RH”.sum
. The clash between checksums is large.
A slightly better checksum is Object#hash
, a method attached to every Ruby object. Since Object#hash
uses a multiplier and bit shifter, its clash is diminished. While it is less predictable than String#sum
, the hash from Object#hash
can still be easily reversed, so don’t expect security from this hash.
As it stands, String#sum
works for character math and Object#hash
works for simplifying storage of Hash keys.
Note: Method Check is a column which investigates usage of a single method available in Ruby or a Ruby library. Ri conventions are used. The octothorpe symbol #
is used to identify instance methods (such as Object#object_id), while the double-colon ::
is used for class methods (such as Object::new.)
Comments are closed for this entry.