Code tagged with hash

Create a Hash from an Array object

Posted by mqj 8 days ago
>> a = [1,2,3,4,5,6,7,8,9,10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> Hash[ *a ]
=> {5=>6, 1=>2, 7=>8, 3=>4, 9=>10}
>> 
?>   b = [ [1,2], [3,4], 5, 6, 7, 8, 9, 10 ]
=> [[1, 2], [3, 4], 5, 6, 7, 8, 9, 10]
>> Hash[ *b ]
=> {5=>6, [1, 2]=>[3, 4], 7=>8, 9=>10}
Language Ruby / Tagged with hash, array

Create a Hash from two Array objects

# Requires Ruby 1.8.7 or higher.

>> keys = [1,2,[3,4]]
=> [1, 2, [3, 4]]
>> values = ['a','b',['c','d']]
=> ["a", "b", ["c", "d"]]
>> Hash[ * keys.zip(values).flatten(1) ]
=> {1=>;"a", [3, 4]=>["c", "d"], 2=>"b"}
Language Ruby / Tagged with hash, array, arrays, zip

Extending Hash with Except and Only

Posted by Chad Humphries about 1 year ago
I first saw this on the RSpec lists, but I can't find who to originally credit.   This little extension to Hash lets you easily get only the key(s) you want out of a hash, or all but certain keys out of the hash.

class Hash
  # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
  def except(*keys)
    self.reject { |k,v|
      keys.include? k.to_sym
    }
  end

  # Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1}
  def only(*keys)
    self.dup.reject { |k,v|
      !keys.include? k.to_sym
    }
  end
end
Language Ruby / Tagged with hash

Compute 32-bit hash with XOR

The following code computes a hash value for a byte array and returns it as an Int32. This can be faster or more useful than MD5, depending on your needs.

Shared Function ComputeInt32XORHash(ByVal Seed As Int32, _
  ByVal Buffer() As Byte, ByVal Index As Integer, _
  ByVal Length As Integer) As Int32

  Dim HashCode As Int32 = Seed

  While Index <= Length - 4
    HashCode = HashCode Xor BitConverter.ToInt32(Buffer, Index)
    Index += 4
  End While

  If Index < Length Then
    Dim Offset As Integer = 0
    Dim LastBlock(3) As Byte

    For Offset = 0 To Length - Index - 1
      LastBlock(Offset) = Buffer(Index + Offset)
    Next
    HashCode = HashCode Xor BitConverter.ToInt32(LastBlock, 0)
  End If

  Return HashCode
End Function
Language VB.NET / Tagged with xor, hash