Class: Array

Inherits:
Object show all
Defined in:
lib/nice/hash/add_to_ruby.rb,
lib/nice/hash/add_to_ruby.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *arguments, &block) ⇒ Object



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/nice/hash/add_to_ruby.rb', line 413

def method_missing(m, *arguments, &block)
  m = m[1..-1].to_sym if m[0] == "_"
  array = []
  no_key = true
  self.map do |hash|
    if hash.is_a?(Hash)
      array << hash[m]
      no_key = false
    else
      array << nil
    end
  end
  if no_key
    super(m, *arguments, &block)
  else
    array
  end
end

Instance Method Details

#bury(where, value) ⇒ Object

Stores a value on the location indicated input:

where: (Array)
value

examples:

my_array.bury([3, 0], "doom") # array of array
my_array.bury([2, 1, :original],"the value to set") #array of array of hash


82
83
84
85
86
87
88
# File 'lib/nice/hash/add_to_ruby.rb', line 82

def bury(where, value)
  me = self
  where[0..-2].each do |key|
    me = me[key]
  end
  me[where[-1]] = value
end

#deep_copy ⇒ Object Also known as: nice_copy

returns a clean copy



117
118
119
# File 'lib/nice/hash/add_to_ruby.rb', line 117

def deep_copy
  NiceHash.deep_clone(self)
end

#json(*keys) ⇒ Object

In case of an array of json strings will return the keys specified. The keys need to be provided as symbols input:

keys:
  1 value with key or an array of keys
    In case the key supplied doesn't exist in the hash then it will be return nil for that one

output:

if keys given: a hash of (keys, values) or the value, if the key is found more than once in the json string, then it will be return a hash of arrays
if no keys given, an empty hash


100
101
102
103
# File 'lib/nice/hash/add_to_ruby.rb', line 100

def json(*keys)
  json_string = "[#{join(",")}]"
  json_string.json(*keys)
end

#nice_filter(keys) ⇒ Object

Filter the array of hashes and returns only the specified keys More info: NiceHash.nice_filter



110
111
112
# File 'lib/nice/hash/add_to_ruby.rb', line 110

def nice_filter(keys)
  NiceHash.nice_filter(self, keys)
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

For Array of Hashes returns an array of values of the hash key specified in case doesn't exist an Array method with the same name The keys can be accessed also adding underscore to avoid problems with existent methods examples for the array of hashes ['Peter', city: 'Madrid', 'Lola', city: 'NYC'] :

my_array.city
my_array._name

Returns:



408
409
410
411
# File 'lib/nice/hash/add_to_ruby.rb', line 408

def respond_to_missing?(method_name, include_private = false)
  sym = (method_name.to_s[0] == "_" ? method_name.to_s[1..-1].to_sym : method_name)
  any? { |elem| elem.is_a?(Hash) && (elem.key?(sym) || elem.key?(sym.to_s)) }
end