Method: Hash#rh_set

Defined in:
lib/ihash.rb

#rh_set(value, *p) ⇒ Object

Recursive Hash Set This function will build a recursive hash according to the ‘*p’ key tree. if yVal is not nil, it will be updated.

  • Args :

    • p : Array of string or symbols. keys tree to follow and check

      existence in yVal.
      
  • Returns :

    • value : the value set.

  • Raises : No exceptions

Example:(implemented in spec)

data = {}.rh_set(:test)            # => {}

data.rh_set(:test, :test2)         # => {:test2 => :test}

data.rh_set(:test, :test2, :test5) # => {:test2 => {:test5 => :test} }

data.rh_set(:test, :test5 )        # => {:test2 => {:test5 => :test},
                                   #     :test5 => :test }

data.rh_set('blabla', :test2, 'text')
                                   # => {:test2 => {:test5 => :test,
                                   #                'text' => 'blabla'},
                                   #     :test5 => :test }


426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/ihash.rb', line 426

def rh_set(value, *p)
  p = p.flatten
  return nil if p.length == 0

  if p.length == 1
    self[p[0]] = value
    return value
  end

  self[p[0]] = {} unless self[p[0]].is_a?(Hash)
  self[p[0]].rh_set(value, p.drop(1))
end