class Hash

Public Class Methods

build(args = nil) click to toggle source

Returns new hash with given arguments. If an array is provided, it will be flattened once. Multi-level arrays are not supported. This method is basically a helper to support different return values of Hash#select: Ruby 1.8.7 returns an array, Ruby 1.9.2 returns a hash.

# File lib/vidibus/core_extensions/hash.rb, line 8
def self.build(args = nil)
  if args.is_a?(::Array)
    args = args.flatten_once
    self[*args]
  elsif args.is_a?(self)
    args
  else
    self.new
  end
end

Public Instance Methods

except(*keys) click to toggle source

Returns a copy of self including all but the given keys.

Example:

{:name => "Rodrigo", :age = 21}.except(:name)  # => {:age => 21}

Inspired by: www.koders.com/ruby/fid80243BF76758F830B298E0E681B082B3408AB185.aspx?s=%22Rodrigo+Kochenburger%22#L9

# File lib/vidibus/core_extensions/hash.rb, line 61
def except(*keys)
  keys.flatten!
  args = self.select { |k,v| !keys.include?(k) }
  Hash.build(args)
end
keys?(*args) click to toggle source

Returns true if hash has all of given keys. It's like Hash#key?, but it accepts several keys.

Example:

{:some => "say", :any => "thing"}.keys?(:some, :any) # => true
# File lib/vidibus/core_extensions/hash.rb, line 95
def keys?(*args)
  for arg in args
    return false unless self[arg]
  end
  return true
end
only(*keys) click to toggle source

Returns a copy of self including only the given keys.

Example:

{:name => "Rodrigo", :age => 21}.only(:name)  # => {:name => "Rodrigo"}

Inspired by: www.koders.com/ruby/fid80243BF76758F830B298E0E681B082B3408AB185.aspx?s=%22Rodrigo+Kochenburger%22#L9 and snippets.dzone.com/posts/show/302

# File lib/vidibus/core_extensions/hash.rb, line 46
def only(*keys)
  keys.flatten!
  args = self.select { |k,v| keys.include?(k) }
  Hash.build(args)
end
to_a_rec() click to toggle source

Returns a nested array. Just like to_a, but nested. Also converts hashes within arrays.

# File lib/vidibus/core_extensions/hash.rb, line 70
def to_a_rec
  array = []
  for key, value in self
    if value.is_a?(Hash)
      value = value.to_a_rec
    elsif value.is_a?(Array)
      a = value.flatten
      value = []
      for v in a
        value << (v.is_a?(Hash) ? v.to_a_rec : v)
      end
    end
    array << [key, value]
  end
  array
end
to_query(namespace = nil) click to toggle source

Returns URL-encoded string of uri params.

Examples:

{:some => :value, :another => "speciál"}.to_uri  # => "some=value&another=speci%C3%A1l"
{:some => {:nested => :thing}}.to_uri            # => "some[nested]=thing"

Stolen from active_record/core_ext. Thanks

# File lib/vidibus/core_extensions/hash.rb, line 28
def to_query(namespace = nil)
  out = collect do |key, value|
    value.to_query(namespace ? "#{namespace}[#{key}]" : key)
  end.sort * "&"
end
Also aliased as: to_uri
to_uri(namespace = nil)
Alias for: to_query