Sha256: 69f4193e721396390d169880a78f0fafdc4227ed1c99f6ffaa01c431f9419d4e

Contents?: true

Size: 1.37 KB

Versions: 10

Compression:

Stored size: 1.37 KB

Contents

# TITLE:
#
#   Hash Constructor Extensions
#
# SUMMARY:
#
#   Alternate constructors for Hash.
#
# CREDIT:
#
#   - Jan Molic
#   - Ara.T.Howard

#
class Hash

  #  Hash which auto initializes it's children.
  #
  #   ah = Hash.autonew
  #   ah['section one']['param one'] = 4
  #   ah['section one']['param two'] = 5
  #   ah['section one']['param three'] = 2
  #   ah['section one']['param four'] = 3
  #
  #   p ah
  #   # {"section one"=>{"param one"=>4, "param four"=>3, "param three"=>2, "param two"=>5}}
  #
  #   p ah['section one'].keys
  #   # ["param one", "param four", "param three", "param two"]
  #

  def self.autonew(*args)
    #new(*args){|a,k| a[k] = self.class::new(*args)}
    leet = lambda { |hsh, key| hsh[key] = new( &leet ) }
    new(*args,&leet)
  end

  # Creates a new hash from two arrays --a keys array and
  # a values array.
  #
  #   Hash.zipnew(["a","b","c"], [1,2,3])
  #     #=> { "a"=>1, "b"=>2, "c"=>3 }
  #
  def self.zipnew(keys,values) # or some better name
    h = {}
    keys.size.times{ |i| h[ keys[i] ] = values[i] }
    h
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TestHashNew < Test::Unit::TestCase

    def test_zipnew
      a = [1,2,3]
      b = [4,5,6]
      assert_equal( {1=>4,2=>5,3=>6}, Hash.zipnew(a,b) )
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.0 lib/core/facets/hash/new.rb
facets-2.0.1 lib/core/facets/hash/new.rb
facets-2.0.2 lib/core/facets/hash/new.rb
facets-2.1.0 lib/core/facets/hash/new.rb
facets-2.1.1 lib/core/facets/hash/new.rb
facets-2.1.2 lib/core/facets/hash/new.rb
facets-2.0.3 lib/core/facets/hash/new.rb
facets-2.0.4 lib/core/facets/hash/new.rb
facets-2.0.5 lib/core/facets/hash/new.rb
facets-2.1.3 lib/core/facets/hash/new.rb