Module: Rearmed::Hash

Defined in:
lib/rearmed/methods.rb

Class Method Summary collapse

Class Method Details

.compact(hash) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/rearmed/methods.rb', line 43

def self.compact(hash)
  if hash.is_a?(::Hash)
    hash.reject{|_, value| value.nil?}
  else
    raise TypeError.new("Invalid object passed to #{__method__}, must be a Hash")
  end
end

.join(hash, delimiter = ', ', &block) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rearmed/methods.rb', line 51

def self.join(hash, delimiter=', ', &block)
  if hash.is_a?(::Hash)
    unless block_given?
      block = ->(k,v){ "#{k}: #{v}" }
    end

    str = ""

    hash.each_with_index do |(k,v), i| 
      val = block.call(k,v)
      unless val.is_a?(::String)
        val = val.to_s
      end
      str << val

      if i+1 < hash.length
        str << delimiter
      end
    end

    return str
  else
    raise TypeError.new("Invalid object passed to #{__method__}, must be a Hash")
  end
end

.only(hash, *keys) ⇒ Object



77
78
79
80
81
82
83
84
# File 'lib/rearmed/methods.rb', line 77

def self.only(hash, *keys)
  if hash.is_a?(::Hash)
    keys.map!{|key| hash.convert_key(key)} if hash.respond_to?(:convert_key, true)
    keys.each_with_object(hash.class.new){|k, new_hash| new_hash[k] = hash[k] if hash.has_key?(k)}
  else
    raise TypeError.new("Invalid object passed to #{__method__}, must be a Hash")
  end
end

.to_struct(hash) ⇒ Object



86
87
88
89
90
91
92
# File 'lib/rearmed/methods.rb', line 86

def self.to_struct(hash)
  if hash.is_a?(::Hash)
    Struct.new(*hash.keys).new(*hash.values)
  else
    raise TypeError.new("Invalid object passed to #{__method__}, must be a Hash")
  end
end