Class | Hash

In:

lib/facets/more/json.rb
lib/facets/more/openobject.rb
lib/facets/more/snapshot.rb
lib/facets/core/kernel/to_data.rb
lib/facets/core/hash/reverse_merge.rb
lib/facets/core/hash/op_div.rb
lib/facets/core/hash/collate.rb
lib/facets/core/hash/having_aquisition.rb
lib/facets/core/hash/each_with_index.rb
lib/facets/core/hash/swapkey.rb
lib/facets/core/hash/op_lshift.rb
lib/facets/core/hash/variablize_keys.rb
lib/facets/core/hash/op_fetch.rb
lib/facets/core/hash/to_h.rb
lib/facets/core/hash/assert_has_only_keys.rb
lib/facets/core/hash/normalize_keys.rb
lib/facets/core/hash/delete_unless.rb
lib/facets/core/hash/replace_each.rb
lib/facets/core/hash/traverse.rb
lib/facets/core/hash/to_ostruct_recurse.rb
lib/facets/core/hash/having_fallback.rb
lib/facets/core/hash/shuffle.rb
lib/facets/core/hash/has_keys.rb
lib/facets/core/hash/join.rb
lib/facets/core/hash/graph.rb
lib/facets/core/hash/at.rb
lib/facets/core/hash/update_values.rb
lib/facets/core/hash/update_each.rb
lib/facets/core/hash/each_with_key.rb
lib/facets/core/hash/stringify_keys.rb
lib/facets/core/hash/has_only_keys.rb
lib/facets/core/hash/to_struct.rb
lib/facets/core/hash/swap.rb
lib/facets/core/hash/delete_values.rb
lib/facets/core/hash/update_keys.rb
lib/facets/core/hash/rand_value.rb
lib/facets/core/hash/assert_has_keys.rb
lib/facets/core/hash/alias.rb
lib/facets/core/hash/rand_key.rb
lib/facets/core/hash/rand_pair.rb
lib/facets/core/hash/slice.rb
lib/facets/core/hash/rekey.rb
lib/facets/core/hash/to_ostruct.rb
lib/facets/core/hash/to_proc.rb
lib/facets/core/hash/weave.rb
lib/facets/core/hash/diff.rb
lib/facets/core/hash/symbolize_keys.rb
lib/facets/core/hash/inverse.rb
lib/facets/core/hash/delete_values_at.rb
lib/facets/core/hash/delete_at.rb
lib/facets/core/hash/op_add.rb
lib/facets/core/hash/op_and.rb
lib/facets/core/hash/op_mul.rb
lib/facets/core/hash/insert.rb
lib/facets/core/hash/pairs_at.rb
lib/facets/core/hash/self/zipnew.rb
lib/facets/core/hash/self/auto.rb

Parent: | Object

### Methods

& * + - [] [] [] []= alias! assert_has_keys assert_has_only_keys at at_rand at_rand! auto collate collate! data_represents data_represents? delete_unless delete_values delete_values_at diff each_with_key fetch fetch from_data graph! has_keys? has_only_keys? having_fallback insert inverse join keys_to_s keys_to_s! keys_to_sym keys_to_sym! normalize_keys normalize_keys! pairs_at pick pick_key pick_pair rand_key rand_key! rand_pair rand_pair! rand_value rand_value! rekey rekey! replace_each restore_snapshot reverse_merge reverse_merge! reverse_update shuffle shuffle! stringify_keys stringify_keys! swap! swapkey! symbolize_keys symbolize_keys! take_snapshot to_data to_h to_json to_object to_openobject to_ostruct to_ostruct_recurse to_proc to_proc_with_reponse to_struct traverse traverse! update_each update_keys update_values variablize_keys variablize_keys! weave with_aquisition zipnew |

### External Aliases

[] | -> | /
| Use division as a fetch notation.
each_with_key | -> | each_with_index
| More appropriate naming and polymorphism with Array. Use each_with_counter for old functionality.
update | -> | <<
| Alias shorthand for update.
values_at | -> | slice

Alias slice to values_at.

      h = { :a => 1, :b => 2, :c => 3 }
      h.slice(:a)      #=> [1]
      h.slice(:a, :b)  #=> [1,2]

delete | -> | delete_at

### Attributes

fallback | [RW] |

### Public Class methods

[](key)
[](key)
auto(*args)

Hash which auto initializes it‘s children.

     ah = Hash.auto
     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"]

fetch(key, *args, &blk)
fetch(key, *args, &blk)
zipnew(keys,values)

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 }

### Public Instance methods

&(other)

Hash intersection. Two hashes intersect when their pairs are equal.

      {:a=>1,:b=>2} & {:a=>1,:c=>3}  #=> {:a=>1}

A hash can also be intersected with an array to insterstec keys only.

      {:a=>1,:b=>2} & [:a,:c]  #=> {:a=>1}

The later form is simalar to pairs_at. The differ only in that pairs_at will return a nil value for a key not in the hash, but #& will not.

*(other)

Like merge operator ’+’ but merges in reverse order.

      h1 = { :a=>1 }
      h2 = { :a=>2, :b=>3 }

      h1 + h2  #=> { :a=>2, :b=>3 }
      h1 * h2  #=> { :a=>1, :b=>3 }

+(other)

Operator for merge.

-(other)

Operator for remove hash paris. If another hash is given the pairs are only removed if both key and value are equal. If an array is given then mathcing keys are removed.

[]( *sliceKeys )

Adds slicing to Hash#[]. If more than one key arguments is given to `Hash#[]`, the return value will be an array of the corresponding values.

      h = { :a => 1, :b => 2, :c => 3 }
      h[:a]            #=> 1
      h[:a, :b]        #=> [1,2]

[]=( *args )

Add slicing to element assignment operator.

      h = {:a=>1, :b=>2, :c=>3}

      h[:a] = 9              #=> 9
      h                      #=> {:a=>9, :b=>2, :c=>3}

      h[:a, :c] = [10,11]    #=> [10,11]
      h                      #=> {:a=>10, :b=>2, :c=>11}

alias!( newkey, oldkey )

Modifies the receiving Hash so that the value previously referred to by oldkey is also referenced by newkey; oldkey is retained in the Hash. If oldkey does not exist as a key in the Hash, no change is effected.

Returns a reference to the Hash.

      foo = { :name=>'Gavin', 'wife'=>:Lisa }
      foo.alias!('name',:name)     => { :name=>'Gavin', 'name'=>'Gavin', 'wife'=>:Lisa }

      foo = { :name=>'Gavin', 'wife'=>:Lisa }
      foo.alias!('spouse','wife')  => { :name=>'Gavin', 'wife'=>:Lisa, 'spouse'=>:Lisa }

      foo = { :name=>'Gavin', 'wife'=>:Lisa }
      foo.alias!('bar','foo')      => { :name=>'Gavin', 'wife'=>:Lisa }

Note that if the oldkey is reassigned, the reference will no longer exist, and the newkey will remain as it was.

assert_has_keys(*check_keys)

Returns true is hash has the given keys, otherwise throws an ArgumentError.

      h = { :a => 1, :b => 2 }
      h.assert_has_keys( :a )   #=> true
      h.assert_has_keys( :c )   #=> ArgumentError

assert_has_only_keys(*check_keys)

Returns true is hash has only then given keys, otherwise throws an ArgumentError.

      h = { :a => 1, :b => 2 }
      h.assert_has_only_keys( :a, :b )   #=> true
      h.assert_has_only_keys( :a )       #=> ArgumentError

at( *sliceKeys )

Alias for #[]

at_rand()

Alias for rand_value

at_rand!()

Alias for rand_value!

collate( {|| ...}

Returns a new hash built by iterating through each key,value pair and updating the new hash.

collate!(&yld)

In place version of collate.

data_represents( klass )
data_represents?( klass )
delete_unless(&block)
delete_values(*values)

Minor modification to Ruby‘s Hash#delete method allowing it to take multiple keys.

      hsh = { :a => 1, :b => 2 }
      hsh.delete_values(1)
      hsh  #=> { :b => 2 }

delete_values_at(*keys, &block)

Minor modification to Ruby‘s Hash#delete method allowing it to take multiple keys.

This works niely with hahs#[] and Hash#[]= facets.

       hsh[:a, :b, :c] = 1, 2, 3

       a, b, c = hsh.delete_values_at(:a, :b, :c)

       [a, b, c]  #=> [1, 2, 3]
       hsh        #=> {}

diff(h2)
each_with_key( &yld )
from_data(snap)
graph!( &blk )

As with Enumerable#graph but acts in place.

has_keys?(*check_keys)

Returns true or false whether the hash contains the given keys.

      h = { :a => 1, :b => 2 }
      h.has_keys?( :a )   #=> true
      h.has_keys?( :c )   #=> false

has_only_keys?(*check_keys)

Returns true if the hash contains only the given keys, otherwise false.

      h = { :a => 1, :b => 2 }
      h.has_only_keys?( :a, :b )   #=> true
      h.has_only_keys?( :a )       #=> false

having_fallback(parent=nil)

Define a fallback object for fetch and #[].

      f = Hash[:b=>2]
      h = Hash[:a=>1].having_fallback(f)
      h[:b] => 2

insert(name, value)

As with store but only if the key isn‘t already in the hash.

inverse()

Create a "true" inverse hash by storing mutliple values in Arrays.

      h = {"a"=>3, "b"=>3, "c"=>3, "d"=>2, "e"=>9, "f"=>3, "g"=>9}

      h.invert                #=> {2=>"d", 3=>"f", 9=>"g"}
      h.inverse               #=> {2=>"d", 3=>["f", "c", "b", "a"], 9=>["g", "e"]}
      h.inverse.inverse       #=> {"a"=>3, "b"=>3, "c"=>3, "d"=>2, "e"=>9, "f"=>3, "g"=>9}
      h.inverse.inverse == h  #=> true

join( pair_divider='', elem_divider='' )
keys_to_s( &filter )

Alias for stringify_keys

keys_to_s!( &filter )

Alias for stringify_keys!

keys_to_sym( &filter )

Alias for symbolize_keys

keys_to_sym!( &filter )

Alias for symbolize_keys!

normalize_keys( &block )

Converts all keys in the Hash accroding to the given block. If the block return `nil` for given key, then that key will be left intact.

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.normalize_keys{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
      foo.inspect                       #=>  { :name =>"Gavin", :wife=>:Lisa }

normalize_keys!( &block )

Synonym for Hash#normalize_keys, but modifies the receiver in place (and returns it).

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.normalize_keys!{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
      foo.inspect                        #=>  { "name"=>"Gavin", "wife"=>:Lisa }

pairs_at( *keys )

Return a new hash with the include entires.

      {:a=>1,:b=>2}.pairs_at(:a,:c)  #=> {:a=>1, :c=>nil}

The later form is equivalent to pairs_at.

pick()

Alias for rand_value!

pick_key()

Alias for rand_key!

pick_pair()

Alias for rand_pair!

rand_key()

Returns a random key.

      {:one => 1, :two => 2, :three => 3}.pick_key  #=> :three

rand_key!()

Delete a random key-value pair, returning the key.

      a = {:one => 1, :two => 2, :three => 3}
      a.pick_key!  #=> :two
      a            #=> {:one => 1, :three => 3}

rand_pair()

Returns a random key-value pair.

      {:one => 1, :two => 2, :three => 3}.pick  #=> [:one, 1]

rand_pair!()

Deletes a random key-value pair and returns that pair.

      a = {:one => 1, :two => 2, :three => 3}
      a.rand_pair!  #=> [:two, 2]
      a             #=> {:one => 1, :three => 3}

rand_value()

Returns a random hash value.

      {:one => 1, :two => 2, :three => 3}.rand_value  #=> 2
      {:one => 1, :two => 2, :three => 3}.rand_value  #=> 1

rand_value!()

Deletes a random key-value pair and returns the value.

      a = {:one => 1, :two => 2, :three => 3}
      a.at_rand!  #=> 2
      a           #=> {:one => 1, :three => 3}

rekey( meth=nil, &block )

Converts all keys in the Hash accroding to the given block. If the block return `nil` for given key, then that key will be left intact.

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.rekey{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
      foo.inspect              #=>  { :name =>"Gavin", :wife=>:Lisa }

rekey!( meth=nil, &block )

Synonym for Hash#rekey, but modifies the receiver in place (and returns it).

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.rekey!{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
      foo.inspect               #=>  { "name"=>"Gavin", "wife"=>:Lisa }

replace_each( {|| ...}

Same as update_each, but deletes the key element first.

restore_snapshot(snap)
reverse_merge(other_hash)

Allows for reverse merging where its the keys in the calling hash that wins over those in the `other_hash`. This is particularly useful for initializing an incoming option hash with default values:

      def setup(options = {})
        options.reverse_merge! :size => 25, :velocity => 10
      end

The default :size and :velocity is only set if the `options` passed in doesn‘t already have those keys set.

reverse_merge!(other_hash)
reverse_update(other_hash)

Alias for reverse_merge!

shuffle()

Returns a copy of the hash with values arranged in new random order.

      h = {:a=>1, :b=>2, :c=>3}
      h.shuffle_hash  #=> {:b=>2, :c=>1, :a>3}

shuffle!()

Destructive shuffle_hash. Arrange the values in a new random order.

      h = {:a => 1, :b => 2, :c => 3}
      h.shuffle_hash!
      h  #=> {:b=>2, :c=>1, :a=>3}

stringify_keys( &filter )

Converts all keys in the Hash to Strings, returning a new Hash. With a `filter` parameter, limits conversion to only a certain selection of keys.

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.stringify_keys    #=>  { "name"=>"Gavin", "wife"=>:Lisa }
      foo.inspect           #=>  { :name =>"Gavin", :wife=>:Lisa }

stringify_keys!( &filter )

Synonym for Hash#stringify_keys, but modifies the receiver in place and returns it. With a `filter` parameter, limits conversion to only a certain selection of keys.

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.stringify_keys!    #=>  { "name"=>"Gavin", "wife"=>:Lisa }
      foo.inspect            #=>  { "name"=>"Gavin", "wife"=>:Lisa }

swap!( key1, key2 )

Swap the values of a pair of keys in place.

      {:a=>1,:b=>2}.swap!  #=> {:a=>2,:b=>1}

swapkey!( newkey, oldkey )

Modifies the receiving Hash so that the value previously referred to by oldkey is referenced by newkey; oldkey is removed from the Hash. If oldkey does not exist as a key in the Hash, no change is effected.

Returns a reference to the Hash.

      foo = { :a=>1, :b=>2 }
      foo.swapkey!('a',:a)       #=> { 'a'=>1, :b=>2 }
      foo.swapkey!('b',:b)       #=> { 'a'=>1, 'b'=>2 }
      foo.swapkey!('foo','bar')  #=> { 'a'=>1, 'b'=>2 }

symbolize_keys( &filter )

Converts all keys in the Hash to Symbols, returning a new Hash. With a `filter`, limits conversion to only a certain selection of keys.

      foo = { :name=>'Gavin', 'wife'=>:Lisa }
      foo.symbolize_keys    #=>  { :name=>"Gavin", :wife=>:Lisa }
      foo.inspect           #=>  { "name" =>"Gavin", "wife"=>:Lisa }

symbolize_keys!( &filter )

Synonym for Hash#symbolize_keys, but modifies the receiver in place and returns it. With a `filter` parameter, limits conversion to only a certain selection of keys.

      foo = { 'name'=>'Gavin', 'wife'=>:Lisa }
      foo.symbolize_keys!    #=>  { :name=>"Gavin", :wife=>:Lisa }
      foo.inspect            #=>  { :name=>"Gavin", :wife=>:Lisa }

take_snapshot()
to_data()
to_h()

Return a rehashing of self.

      {"a"=>1,"b"=>2}.to_h  #=> {"b"=>2,"a"=>1}

to_json(state = nil, depth = 0)

Returns a JSON string containing a JSON object, that is unparsed from this Hash instance. state is a JSON::State object, that can also be used to configure the produced JSON string output further. depth is used to find out nesting depth, to indent accordingly.

to_object( klass=nil )
to_openobject()

Convert a Hash into an OpenObject.

to_ostruct()

Turns a hash into a generic object using an OpenStruct.

      o = { 'a' => 1 }.to_ostruct
      o.a  #=> 1

to_ostruct_recurse( exclude={} )

Like to_ostruct but recusively objectifies all hash elements as well.

        o = { 'a' => { 'b' => 1 } }.to_ostruct_recurse
        o.a.b  #=> 1

The `exclude` parameter is used internally to prevent infinite recursion and is not intended to be utilized by the end-user. But for more advance use, if there is a particular subhash you would like to prevent from being converted to an OpoenStruct then include it in the `exclude` hash referencing itself. Eg.

        h = { 'a' => { 'b' => 1 } }
        o = h.to_ostruct_recurse( { h['a'] => h['a'] } )
        o.a['b']  #=> 1

to_proc()

Constructs a Proc object from a hash such that the parameter of the Proc is assigned the hash keys as attributes.

      h = { :a => 1 }
      p = h.to_proc
      o = OpenStruct.new
      p.call(o)
      o.a  #=> 1

to_proc_with_reponse()
to_struct(struct_name)

A method to convert a Hash into a Struct.

      h = {:name=>"Dan","age"=>33,"rank"=>"SrA","grade"=>"E4"}
      s = h.to_struct("Foo")

traverse(&b)

Returns a new hash created by traversing the hash and its subhashes, executing the given block on the key and value. The block should return a 2-element array of the form +[key, value]+.

      h = { "A"=>"A", "B"=>"B" }
      g = h.traverse { |k,v| [k.downcase, v] }
      g  #=> { "a"=>"A", "b"=>"B" }

traverse!(&b)

In place version of traverse, which traverses the hash and its subhashes, executing the given block on the key and value.

      h = { "A"=>"A", "B"=>"B" }
      h.traverse! { |k,v| [k.downcase, v] }
      h  #=> { "a"=>"A", "b"=>"B" }

update_each( {|| ...}

Iterates through each pair and updates a the hash in place. This is formally equivalent to collate! But does not use collate to accomplish the task. Hence update_each is probably a bit faster.

      # TODO

update_keys() {|k| ...}
update_values() {|v| ...}
variablize_keys( of_class=nil )

Converts all keys in the Hash to be String values, returning a new Hash. With a from_class parameter, limits conversion to only a certain class of keys. It defaults to nil which convert any key class.

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.variablize_keys    #=>  { "@name"=>"Gavin", "@wife"=>:Lisa }
      foo.inspect            #=>  { :name =>"Gavin", :wife=>:Lisa }

variablize_keys!( of_class=nil )

Synonym for Hash#keys_to_string, but modifies the receiver in place (and returns it). With a from_class parameter, limits conversion to only a certain class of keys. It defaults to nil which convert any key class.

      foo = { :name=>'Gavin', :wife=>:Lisa }
      foo.variablize_keys!   #=>  { "@name"=>"Gavin", "@wife"=>:Lisa }
      foo.inspect            #=>  { "@name"=>"Gavin", "@wife"=>:Lisa }

weave(h)

Weaves two hashes producing a new hash. The two hashes need to be compatible according to the following rules for each node:

      <tt>
      hash, hash => hash (recursive +)
      hash, array => error
      hash, value => error
      array, hash => error
      array, array => array + array
      array, value => array << value
      value, hash => error
      value, array => array.unshift(valueB)
      valueA, valueB => valueB
      </tt>

Example:

      # to do

with_aquisition(fallback)

Define a fallback object for fetch and #[].

      f = Hash[:b=>2]
      h = Hash[:a=>1].having_aquisition(f)
      h[:b] => 2

|(other)

Operator for reverse_merge.

[Validate]