Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/std++/main.rb

Overview

Ruby default Hash class

Instance Method Summary collapse

Instance Method Details

#debug_outObject

Returns hash as 'pretty generated' JSON String with replaced JSON(':' to '=>' and 'null' to 'nil')



11
12
13
# File 'lib/std++/main.rb', line 11

def debug_out
    JSON.pretty_generate(self).gsub("\": ", "\" => ").gsub(" => null", " => nil")
end

#get(*keys) ⇒ Array

Returns array of values with given keys

Parameters:

  • keys (Array)
    • Array of values

Returns:



33
34
35
36
37
# File 'lib/std++/main.rb', line 33

def get *keys
    keys.collect do | key |
        self[key]
    end
end

#outObject

Returns hash as 'pretty generated' JSON String



7
8
9
# File 'lib/std++/main.rb', line 7

def out
    JSON.pretty_generate(self)
end

#to_one_templateObject

Transforms Hash to OpenNebula Template. Only two layers allowed => 2, 'DISK' => {'SIZE' => '64'} -> CPU = “2” DISK = [

SIZE = "64" ]

Examples:

VM hash to template



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/std++/main.rb', line 51

def to_one_template
    result = ""
    self.each do | key, value |
        key = key.to_s.upcase
        if value.class == String || value.class == Fixnum then
            result += "#{key}=\"#{value.to_s.gsub("\"", "\\\"")}\"\n"
        elsif value.class == Hash then
            result += "#{key}=[\n"
            size = value.size - 1
            value.each_with_index do | el, i |
                result += "  #{el[0]}=\"#{el[1].to_s.gsub("\"", "\\\"")}\"#{i == size ? '' : ",\n"}"
            end
            result += " ]\n"
        elsif value.class == Array then
            value.each do | el |
                result += { key => el}.to_one_template + "\n"
            end
        end
    end
    result.chomp!
end

#to_s!Hash

Replaces all keys with string keys

Returns:



24
25
26
27
28
29
# File 'lib/std++/main.rb', line 24

def to_s!
    self.keys.each do |key| 
        self[key.to_s] = self.delete key if key.class != String
    end
    self
end

#to_sym!Hash

Replaces string keys with symbol keys

Returns:



16
17
18
19
20
21
# File 'lib/std++/main.rb', line 16

def to_sym!
    self.keys.each do |key| 
        self[key.to_sym] = self.delete key if key.class == String
    end
    self
end

#without(*keys) ⇒ Object

Returns Hash copy without given keys



40
41
42
43
44
# File 'lib/std++/main.rb', line 40

def without(*keys)
    cpy = self.dup
    keys.each { |key| cpy.delete(key) }
    cpy
end