In Files

  • mrbgems/mruby-hash-ext/mrblib/hash.rb
  • mrblib/hash.rb

Hash

Hash is enumerable

ISO 15.2.13.3

Public Class Methods

Hash[ key, value, ... ] → new_hash click to toggle source
Hash[ [ [key, value], ... ] ] → new_hash
Hash[ object ] → new_hash

Creates a new hash populated with the given objects.

Similar to the literal { key => value, ... }. In the first form, keys and values occur in pairs, so there must be an even number of arguments.

The second and third form take a single argument which is either an array of key-value pairs or an object convertible to a hash.

Hash[“a”, 100, “b”, 200] #=> {“a”=>100, “b”=>200} Hash[ [ [“a”, 100], [“b”, 200] ] ] #=> {“a”=>100, “b”=>200} Hash[“a” => 100, “b” => 200] #=> {“a”=>100, “b”=>200}

 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 26
def self.[](*object)
  length = object.length
  if length == 1
    o = object[0]
    if o.respond_to?(:to_hash)
      h = Hash.new
      object[0].to_hash.each { |k, v| h[k] = v }
      return h
    elsif o.respond_to?(:to_a)
      h = Hash.new
      o.to_a.each do |i|
        raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a)
        k, v = nil
        case i.size
        when 2
          k = i[0]
          v = i[1]
        when 1
          k = i[0]
        else
          raise ArgumentError, "invalid number of elements (#{i.size} for 1..2)"
        end
        h[k] = v
      end
      return h
    end
  end
  unless length % 2 == 0
    raise ArgumentError, 'odd number of arguments for Hash'
  end
  h = Hash.new
  0.step(length - 2, 2) do |i|
    h[object[i]] = object[i + 1]
  end
  h
end
            

Public Instance Methods

==(hash) click to toggle source
Equality---Two hashes are equal if they each contain the same number
of keys and if each key-value pair is equal to (according to
<code>Object#==</code>) the corresponding elements in the other
hash.

ISO 15.2.13.4.1

 
               # File mrblib/hash.rb, line 13
def ==(hash)
  return true if self.equal?(hash)
  begin
    hash = hash.to_hash
  rescue NoMethodError
    return false
  end
  return false if self.size != hash.size
  self.each do |k,v|
    return false unless hash.key?(k)
    return false unless self[k] == hash[k]
  end
  return true
end
            
__update(h) click to toggle source
 
               # File mrblib/hash.rb, line 322
def __update(h)
  h.each_key{|k| self[k] = h[k]}
  self
end
            
_inspect() click to toggle source

internal method for Hash inspection

 
               # File mrblib/hash.rb, line 196
def _inspect
  return "{}" if self.size == 0
  "{"+self.map {|k,v|
    k._inspect + "=>" + v._inspect
  }.join(", ")+"}"
end
            
delete(key, &block) click to toggle source

Delete the element with the key key. Return the value of the element if key was found. Return nil if nothing was found. If a block is given, call the block with the value of the element.

ISO 15.2.13.4.8

 
               # File mrblib/hash.rb, line 56
def delete(key, &block)
  if block && !self.has_key?(key)
    block.call(key)
  else
    self.__delete(key)
  end
end
            
delete_if {| key, value | block } → hsh click to toggle source
delete_if → an_enumerator

Deletes every key-value pair from hsh for which block evaluates to true.

If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200, "c" => 300 }
h.delete_if {|key, value| key >= "b" }   #=> {"a"=>100}
 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 154
def delete_if(&block)
  return to_enum :delete_if unless block_given?

  self.each do |k, v|
    self.delete(k) if block.call(k, v)
  end 
  self
end
            
each {| key, value | block } → hsh click to toggle source
each_pair {| key, value | block } → hsh
each → an_enumerator
each_pair → an_enumerator

Calls the given block for each element of self and pass the key and value of each element.

If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200 }
h.each {|key, value| puts "#{key} is #{value}" }

produces:

a is 100 b is 200

ISO 15.2.13.4.9

 
               # File mrblib/hash.rb, line 86
def each(&block)
  return to_enum :each unless block_given?

  keys = self.keys
  vals = self.values
  len = self.size
  i = 0
  while i < len
    block.call [keys[i], vals[i]]
    i += 1
  end
  self
end
            
Also aliased as: each_pair
each_key {| key | block } → hsh click to toggle source
each_key → an_enumerator

Calls the given block for each element of self and pass the key of each element.

If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200 }
h.each_key {|key| puts key }

produces:

a
b

ISO 15.2.13.4.10

 
               # File mrblib/hash.rb, line 119
def each_key(&block)
  return to_enum :each_key unless block_given?

  self.keys.each{|k| block.call(k)}
  self
end
            
each_pair(&block) click to toggle source

ISO does not define #each_pair, so #each_pair is defined in gem.

Alias for: each
each_value {| value | block } → hsh click to toggle source
each_value → an_enumerator

Calls the given block for each element of self and pass the value of each element.

If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200 }
h.each_value {|value| puts value }

produces:

100
200

ISO 15.2.13.4.11

 
               # File mrblib/hash.rb, line 145
def each_value(&block)
  return to_enum :each_value unless block_given?

  self.keys.each{|k| block.call(self[k])}
  self
end
            
eql?(hash) click to toggle source

Returns true if hash and other are both hashes with the same content compared by eql?.

ISO 15.2.13.4.32 (x)

 
               # File mrblib/hash.rb, line 33
def eql?(hash)
  return true if self.equal?(hash)
  begin
    hash = hash.to_hash
  rescue NoMethodError
    return false
  end
  return false if self.size != hash.size
  self.each do |k,v|
    return false unless hash.key?(k)
    return false unless self[k].eql?(hash[k])
  end
  return true
end
            
fetch(key [, default] ) → obj click to toggle source
fetch(key) {| key | block } → obj

Returns a value from the hash for the given key. If the key can't be found, there are several options: With no other arguments, it will raise an KeyError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.

h = { "a" => 100, "b" => 200 }
h.fetch("a")                            #=> 100
h.fetch("z", "go fish")                 #=> "go fish"
h.fetch("z") { |el| "go fish, #{el}"}   #=> "go fish, z"

The following example shows that an exception is raised if the key is not found and a default value is not supplied.

h = { "a" => 100, "b" => 200 }
h.fetch("z")

produces:

prog.rb:2:in 'fetch': key not found (KeyError)
 from prog.rb:2
 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 126
def fetch(key, none=NONE, &block)
  unless self.key?(key)
    if block
      block.call
    elsif none != NONE
      none
    else
      raise RuntimeError, "Key not found: #{key}"
    end
  else
    self[key]
  end
end
            
flatten → an_array click to toggle source
flatten(level) → an_array

Returns a new array that is a one-dimensional flattening of this hash. That is, for every key or value that is an array, extract its elements into the new array. Unlike Array#flatten, this method does not flatten recursively by default. The optional level argument determines the level of recursion to flatten.

a =  {1=> "one", 2 => [2,"two"], 3 => "three"}
a.flatten    # => [1, "one", 2, [2, "two"], 3, "three"]
a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 179
def flatten(level=1)
  self.to_a.flatten(level)
end
            
initialize_copy(hash) click to toggle source

ISO 15.2.13.4.17

Alias for: replace
inspect() click to toggle source

Return the contents of this hash as a string.

ISO 15.2.13.4.30 (x)

 
               # File mrblib/hash.rb, line 206
def inspect
  begin
    self._inspect
  rescue SystemStackError
    "{...}"
  end
end
            
Also aliased as: to_s
invert → new_hash click to toggle source

Returns a new hash created by using hsh's values as keys, and the keys as values.

h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
h.invert   #=> {0=>"a", 100=>"m", 200=>"d", 300=>"y"}
 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 194
def invert
  h = Hash.new
  self.each {|k, v| h[v] = k }
  h
end
            
keep_if {| key, value | block } → hsh click to toggle source
keep_if → an_enumerator

Deletes every key-value pair from hsh for which block evaluates to false.

If no block is given, an enumerator is returned instead.

 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 211
def keep_if(&block)
  return to_enum :keep_if unless block_given?

  keys = []
  self.each do |k, v|
    unless block.call([k, v])
      self.delete(k)
    end
  end
  self
end
            
key(value) → key click to toggle source

Returns the key of an occurrence of a given value. If the value is not found, returns nil.

h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
h.key(200)   #=> "b"
h.key(300)   #=> "c"
h.key(999)   #=> nil
 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 236
def key(val)
  self.each do |k, v|
    return k if v == val
  end
  nil
end
            
merge(other, &block) click to toggle source

Return a hash which contains the content of self and other. If a block is given it will be called for each element with a duplicate key. The value of the block will be the final value of this element.

ISO 15.2.13.4.22

 
               # File mrblib/hash.rb, line 180
def merge(other, &block)
  h = {}
  raise TypeError, "can't convert argument into Hash" unless other.respond_to?(:to_hash)
  other = other.to_hash
  self.each_key{|k| h[k] = self[k]}
  if block
    other.each_key{|k|
      h[k] = (self.has_key?(k))? block.call(k, self[k], other[k]): other[k]
    }
  else
    other.each_key{|k| h[k] = other[k]}
  end
  h
end
            
merge!(other_hash) → hsh click to toggle source
merge!(other_hash){|key, oldval, newval| block} → hsh

Adds the contents of other_hash to hsh. If no block is specified, entries with duplicate keys are overwritten with the values from other_hash, otherwise the value of each duplicate key is determined by calling the block with the key, its value in hsh and its value in other_hash.

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge!(h2) { |key, v1, v2| v1 }
                #=> {"a"=>100, "b"=>200, "c"=>300}
 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 84
def merge!(other, &block)
  raise TypeError, "can't convert argument into Hash" unless other.respond_to?(:to_hash)
  if block
    other.each_key{|k|
      self[k] = (self.has_key?(k))? block.call(k, self[k], other[k]): other[k]
    }
  else
    other.each_key{|k| self[k] = other[k]}
  end
  self
end
            
Also aliased as: update
reject {|key, value| block} → a_hash click to toggle source
reject → an_enumerator

Returns a new hash consisting of entries for which the block returns false.

If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200, "c" => 300 }
h.reject {|k,v| k < "b"}  #=> {"b" => 200, "c" => 300}
h.reject {|k,v| v > 100}  #=> {"a" => 100}

1.8/1.9 #reject returns Hash; ISO says nothing.

 
               # File mrblib/hash.rb, line 257
def reject(&b)
  return to_enum :reject unless block_given?

  h = {}
  self.each{|k,v|
    unless b.call([k, v])
      h[k] = v
    end
  }
  h
end
            
reject! {| key, value | block } → hsh or nil click to toggle source
reject! → an_enumerator

Equivalent to Hash#delete_if, but returns nil if no changes were made.

1.8/1.9 #reject! returns Hash; ISO says nothing.

 
               # File mrblib/hash.rb, line 226
def reject!(&b)
  return to_enum :reject! unless block_given?

  keys = []
  self.each{|k,v|
    if b.call([k, v])
      keys.push(k)
    end
  }
  return nil if keys.size == 0
  keys.each{|k|
    self.delete(k)
  }
  self
end
            
replace(hash) click to toggle source

Replaces the contents of hsh with the contents of other hash

ISO 15.2.13.4.23

 
               # File mrblib/hash.rb, line 156
def replace(hash)
  self.clear
  hash = hash.to_hash
  hash.each_key{|k|
    self[k] = hash[k]
  }
  if hash.default_proc
    self.default_proc = hash.default_proc
  else
    self.default = hash.default
  end
  self
end
            
Also aliased as: initialize_copy
select {|key, value| block} → a_hash click to toggle source
select → an_enumerator

Returns a new hash consisting of entries for which the block returns true.

If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200, "c" => 300 }
h.select {|k,v| k > "a"}  #=> {"b" => 200, "c" => 300}
h.select {|k,v| v < 200}  #=> {"a" => 100}

1.9 #select returns Hash; ISO says nothing

 
               # File mrblib/hash.rb, line 310
def select(&b)
  return to_enum :select unless block_given?

  h = {}
  self.each{|k,v|
    if b.call([k, v])
      h[k] = v
    end
  }
  h
end
            
select! {| key, value | block } → hsh or nil click to toggle source
select! → an_enumerator

Equivalent to Hash#keep_if, but returns nil if no changes were made.

1.9 #select! returns Hash; ISO says nothing.

 
               # File mrblib/hash.rb, line 279
def select!(&b)
  return to_enum :select! unless block_given?

  keys = []
  self.each{|k,v|
    unless b.call([k, v])
      keys.push(k)
    end
  }
  return nil if keys.size == 0
  keys.each{|k|
    self.delete(k)
  }
  self
end
            
to_h → hsh or new_hash click to toggle source

Returns self. If called on a subclass of Hash, converts the receiver to a Hash object.

 
               # File mrbgems/mruby-hash-ext/mrblib/hash.rb, line 250
def to_h
  self
end
            
to_s() click to toggle source

ISO 15.2.13.4.31 (x)

Alias for: inspect
update(other, &block) click to toggle source
Alias for: merge!