Class: Hash

Inherits:
Object show all
Defined in:
lib/rubyexts/hash.rb

Instance Method Summary collapse

Instance Method Details

#deep_symbolize_keysHash

Return duplication of self with all keys recursively converted to symbols

Returns:

  • (Hash)

    A hash with all keys transformed into symbols even in inner hashes

Author:

  • Botanicus

Since:

  • 0.0.2



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rubyexts/hash.rb', line 30

def deep_symbolize_keys
  self.inject(Hash.new) do |result, array|
    key, value = array.first, array.last
    if value.respond_to?(:symbolize_keys)
      result[key.to_sym] = value.symbolize_keys
    else
      result[key.to_sym] = value
    end
    result
  end
end

#deep_symbolize_keys!Hash

Recursively replace keys in self by coresponding symbols

Returns:

  • (Hash)

    A hash with all keys transformed into symbols even in inner hashes

Author:

  • Botanicus

Since:

  • 0.0.2



47
48
49
# File 'lib/rubyexts/hash.rb', line 47

def deep_symbolize_keys!
  self.replace(self.deep_symbolize_keys)
end

#except(*rejected) ⇒ Hash

Create a hash with all key/value pairs in receiver except rejected

{ :one => 1, :two => 2, :three => 3 }.except(:one)
 #=> { :two => 2, :three => 3 }

Parameters:

Returns:

  • (Hash)

    A new hash without the selected keys.



175
176
177
178
179
# File 'lib/rubyexts/hash.rb', line 175

def except(*rejected)
  hash = self.dup
  rejected.each {|k| hash.delete(k) }
  hash
end

#extract!(*args) ⇒ Array<Object>

Returns the value of self for each argument and deletes those entries.

Examples:

hash = {one: 1, two: 2, three: 3}
hash.extract!(:one, :two) # => [1, 2]
hash                      # => {:three => 3}

Parameters:

  • the (*args)

    keys whose values should be extracted and deleted.

Returns:

  • (Array<Object>)

    The values of the provided arguments in corresponding order.

Author:

  • Botanicus

Since:

  • 0.0.2



62
63
64
65
66
# File 'lib/rubyexts/hash.rb', line 62

def extract!(*args)
  args.map do |arg|
    self.delete(arg)
  end
end

#get(*keys) ⇒ Object?

Simplier syntax for code such as params && params[:title]

Examples:

{a: {b: 1}}.get(:a, :b)     # => 1
{a: {b: 1}}.get(:a, :b, :c) # => IndexError
{a: {b: 1}}.get(:a, :c)     # => nil

Parameters:

  • First (Object)

    argument is the key of the hash, the second one the key of the inner hash selected by the first key etc.

Returns:

  • (Object, nil)

    The value of the most inner hash if found or nil.

Raises:

  • (ArgumentError)

    If you don’t specify keys.

  • (IndexError)

    If you work with final result as with hash, so basically you are trying to call fetch method on string or whatever.

Author:

  • Jakub Stastny aka Botanicus

Since:

  • 0.0.3



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/rubyexts/hash.rb', line 130

def get(*keys)
  raise ArgumentError, "You must specify at least one key" if keys.empty?
  keys.inject(self) do |object, key|
    # Hash#fetch works similar as Hash#[], but [] method is
    # defined for too many objects, also strings and even numbers
    if object.respond_to?(:fetch)
      begin
        object.fetch(key)
      # Hash#fetch raise IndexError if key doesn't exist
      rescue IndexError
        return nil
      end
    else
      raise IndexError, "Object #{object.inspect} isn't hash-like collection"
    end
  end
end

#only(*allowed) ⇒ Hash

Create a hash with only key/value pairs in receiver and allowed

{ :one => 1, :two => 2, :three => 3 }.only(:one)    #=> { :one => 1 }

Parameters:

Returns:

  • (Hash)

    A new hash with only the selected keys.



158
159
160
161
162
# File 'lib/rubyexts/hash.rb', line 158

def only(*allowed)
  hash = {}
  allowed.each {|k| hash[k] = self[k] if self.has_key?(k) }
  hash
end

#reverse_merge(another) ⇒ String

Returns Merge self into hash given as argument.

Returns:

  • (String)

    Merge self into hash given as argument

Author:

  • Botanicus

Since:

  • 0.0.2



89
90
91
# File 'lib/rubyexts/hash.rb', line 89

def reverse_merge(another)
  another.merge(self)
end

#reverse_merge!(another) ⇒ String

Returns Replace self by result of merge self into hash given as argument.

Returns:

  • (String)

    Replace self by result of merge self into hash given as argument

Author:

  • Botanicus

Since:

  • 0.0.2



96
97
98
# File 'lib/rubyexts/hash.rb', line 96

def reverse_merge!(another)
  self.replace(self.reverse_merge(another))
end

#symbolize_keysHash

Return duplication of self with all keys non-recursively converted to symbols

Returns:

  • (Hash)

    A hash with all keys transformed into symbols

Author:

  • Botanicus

Since:

  • 0.0.2



9
10
11
12
13
14
# File 'lib/rubyexts/hash.rb', line 9

def symbolize_keys
  self.inject(Hash.new) do |result, array|
    result[array.first.to_sym] = array.last
    result
  end
end

#symbolize_keys!Hash

Replace keys in self by coresponding symbols

Returns:

  • (Hash)

    A hash with all keys transformed into symbols

Author:

  • Botanicus

Since:

  • 0.0.2



21
22
23
# File 'lib/rubyexts/hash.rb', line 21

def symbolize_keys!
  self.replace(self.symbolize_keys)
end

#to_html_attrsString

Returns A string formatted for HTML attributes.

Examples:

{class: "inner", id: "post-#{@post.id}"}.to_html_attrs # => "class='inner' id='post-1'"

Returns:

  • (String)

    A string formatted for HTML attributes

Author:

  • Botanicus

Since:

  • 0.0.2



73
74
75
# File 'lib/rubyexts/hash.rb', line 73

def to_html_attrs
  self.map { |key, value| "#{key}='#{value}'" }.join(" ")
end

#to_nativeObject

Deprecated.

Author:

  • Botanicus

Since:

  • 0.0.2



103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/rubyexts/hash.rb', line 103

def to_native
  self.each do |key, value|
    value = case value
    when "true" then true
    when "false" then false
    when "nil" then nil
    when /^\d+$/ then value.to_i
    when /^\d+\.\d+$/ then value.to_f
    else value end
    self[key.to_sym] = value
  end
  return self
end

#to_url_attrsString

Returns A string formatted for URL.

Examples:

{action: "rate", rating: 2}.to_url_attrs # => "action=rate&rating=2"

Returns:

  • (String)

    A string formatted for URL

Author:

  • Botanicus

Since:

  • 0.0.2



82
83
84
# File 'lib/rubyexts/hash.rb', line 82

def to_url_attrs
  self.map { |key, value| "#{key}=#{value}" }.join("&")
end