Class: Hash

Inherits:
Object show all
Includes:
Enumerable
Defined in:
mrblib/hash.rb,
src/hash.c,
mrblib/hash.rb,
mrbgems/mruby-hash-ext/mrblib/hash.rb

Overview

Hash is enumerable

ISO 15.2.13.3

Constant Summary

Constants included from Enumerable

Enumerable::NONE

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Enumerable

#all?, #any?, #collect, #count, #cycle, #detect, #drop, #drop_while, #each_cons, #each_slice, #each_with_index, #each_with_object, #entries, #find_all, #find_index, #first, #flat_map, #grep, #group_by, #hash, #inject, #lazy, #max, #max_by, #min, #min_by, #minmax, #minmax_by, #none?, #one?, #partition, #reverse_each, #sort, #sort_by, #take, #take_while, to_h, #uniq, #zip

Constructor Details

#newObject #new(obj) ⇒ Object #new {|hash, key| ... } ⇒ Object

Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn’t correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block’s responsibility to store the value in the hash if required.

h = Hash.new("Go Fish")
h["a"] = 100
h["b"] = 200
h["a"]           #=> 100
h["c"]           #=> "Go Fish"
# The following alters the single default object
h["c"].upcase!   #=> "GO FISH"
h["d"]           #=> "GO FISH"
h.keys           #=> ["a", "b"]

# While this creates a new default object each time
h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
h["c"]           #=> "Go Fish: c"
h["c"].upcase!   #=> "GO FISH: C"
h["d"]           #=> "Go Fish: d"
h.keys           #=> ["c", "d"]

Overloads:


330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'src/hash.c', line 330

static mrb_value
mrb_hash_init(mrb_state *mrb, mrb_value hash)
{
  mrb_value block, ifnone;
  mrb_bool ifnone_p;

  ifnone = mrb_nil_value();
  mrb_get_args(mrb, "&|o?", &block, &ifnone, &ifnone_p);
  mrb_hash_modify(mrb, hash);
  if (!mrb_nil_p(block)) {
    if (ifnone_p) {
      mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
    }
    RHASH(hash)->flags |= MRB_HASH_PROC_DEFAULT;
    ifnone = block;
  }
  if (!mrb_nil_p(ifnone)) {
    RHASH(hash)->flags |= MRB_HASH_DEFAULT;
    mrb_iv_set(mrb, hash, mrb_intern_lit(mrb, "ifnone"), ifnone);
  }
  return hash;
}

Class Method Details

.[](*object) ⇒ Object

call-seq: Hash[ key, value, … ] -> new_hash 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}

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 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 = self.new
      object[0].to_hash.each { |k, v| h[k] = v }
      return h
    elsif o.respond_to?(:to_a)
      h = self.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 = self.new
  0.step(length - 2, 2) do |i|
    h[object[i]] = object[i + 1]
  end
  h
end

.try_convert(obj) ⇒ Object

call-seq: Hash.try_convert(obj) -> hash or nil

Try to convert obj into a hash, using to_hash method. Returns converted hash or nil if obj cannot be converted for any reason.

Hash.try_convert({1=>2})   # => {1=>2}
Hash.try_convert("1=>2")   # => nil

74
75
76
77
78
79
80
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 74

def self.try_convert(obj)
  if obj.respond_to?(:to_hash)
    obj.to_hash
  else
    nil
  end
end

Instance Method Details

#<(hash) ⇒ Object

call-seq: hash < other -> true or false

Returns true if hash is subset of other.

h1 = {a:1, b:2}
h2 = {a:1, b:2, c:3}
h1 < h2    #=> true
h2 < h1    #=> false
h1 < h1    #=> false

302
303
304
305
306
307
308
309
310
311
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 302

def <(hash)
  begin
    hash = hash.to_hash
  rescue NoMethodError
    raise TypeError, "can't convert #{hash.class} to Hash"
  end
  size < hash.size and all? {|key, val|
    hash.key?(key) and hash[key] == val
  }
end

#<=(hash) ⇒ Object

call-seq: hash <= other -> true or false

Returns true if hash is subset of other or equals to other.

h1 = {a:1, b:2}
h2 = {a:1, b:2, c:3}
h1 <= h2   #=> true
h2 <= h1   #=> false
h1 <= h1   #=> true

326
327
328
329
330
331
332
333
334
335
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 326

def <=(hash)
  begin
    hash = hash.to_hash
  rescue NoMethodError
    raise TypeError, "can't convert #{hash.class} to Hash"
  end
  size <= hash.size and all? {|key, val|
    hash.key?(key) and hash[key] == val
  }
end

#==(hash) ⇒ Object

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 Object#==) the corresponding elements in the other hash.

ISO 15.2.13.4.1


13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 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

#>(hash) ⇒ Object

call-seq: hash > other -> true or false

Returns true if other is subset of hash.

h1 = {a:1, b:2}
h2 = {a:1, b:2, c:3}
h1 > h2    #=> false
h2 > h1    #=> true
h1 > h1    #=> false

350
351
352
353
354
355
356
357
358
359
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 350

def >(hash)
  begin
    hash = hash.to_hash
  rescue NoMethodError
    raise TypeError, "can't convert #{hash.class} to Hash"
  end
  size > hash.size and hash.all? {|key, val|
    key?(key) and self[key] == val
  }
end

#>=(hash) ⇒ Object

call-seq: hash >= other -> true or false

Returns true if other is subset of hash or equals to hash.

h1 = {a:1, b:2}
h2 = {a:1, b:2, c:3}
h1 >= h2   #=> false
h2 >= h1   #=> true
h1 >= h1   #=> true

374
375
376
377
378
379
380
381
382
383
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 374

def >=(hash)
  begin
    hash = hash.to_hash
  rescue NoMethodError
    raise TypeError, "can't convert #{hash.class} to Hash"
  end
  size >= hash.size and hash.all? {|key, val|
    key?(key) and self[key] == val
  }
end

#[](key) ⇒ Object

Element Reference—Retrieves the value object corresponding to the key object. If not found, returns the default value (see Hash::new for details).

h = { “a” => 100, “b” => 200 } h[“a”] #=> 100 h[“c”] #=> nil


367
368
369
370
371
372
373
374
# File 'src/hash.c', line 367

static mrb_value
mrb_hash_aget(mrb_state *mrb, mrb_value self)
{
  mrb_value key;

  mrb_get_args(mrb, "o", &key);
  return mrb_hash_get(mrb, self, key);
}

#[]=(key) ⇒ Object #store(key, value) ⇒ Object

Element Assignment—Associates the value given by value with the key given by key. key should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen).

h = { "a" => 100, "b" => 200 }
h["a"] = 9
h["c"] = 4
h   #=> {"a"=>9, "b"=>200, "c"=>4}

669
670
671
672
673
674
675
676
677
# File 'src/hash.c', line 669

static mrb_value
mrb_hash_aset(mrb_state *mrb, mrb_value self)
{
  mrb_value key, val;

  mrb_get_args(mrb, "oo", &key, &val);
  mrb_hash_set(mrb, self, key, val);
  return val;
}

#delete(key) ⇒ Object #delete(key) {|key| ... } ⇒ Object

Deletes and returns a key-value pair from hsh whose key is equal to key. If the key is not found, returns the default value. If the optional code block is given and the key is not found, pass in the key and return the result of block.

h = { "a" => 100, "b" => 200 }
h.delete("a")                              #=> 100
h.delete("z")                              #=> nil
h.delete("z") { |el| "#{el} not found" }   #=> "z not found"

Overloads:

  • #delete(key) {|key| ... } ⇒ Object

    Yields:


572
573
574
575
576
577
578
579
580
# File 'src/hash.c', line 572

static mrb_value
mrb_hash_delete(mrb_state *mrb, mrb_value self)
{
  mrb_value key;

  mrb_get_args(mrb, "o", &key);
  mrb_hash_modify(mrb, self);
  return mrb_hash_delete_key(mrb, self, key);
}

#__update(h) ⇒ Object


346
347
348
349
# File 'mrblib/hash.rb', line 346

def __update(h)
  h.each_key{|k| self[k] = h[k]}
  self
end

#_inspectObject

internal method for Hash inspection


197
198
199
200
201
202
# File 'mrblib/hash.rb', line 197

def _inspect
  return "{}" if self.size == 0
  "{"+self.map {|k,v|
    k._inspect + "=>" + v._inspect
  }.join(", ")+"}"
end

#clearHash

Removes all key-value pairs from hsh.

h = { "a" => 100, "b" => 200 }   #=> {"a"=>100, "b"=>200}
h.clear                          #=> {}

Returns:


640
641
642
643
644
645
646
647
648
# File 'src/hash.c', line 640

MRB_API mrb_value
mrb_hash_clear(mrb_state *mrb, mrb_value hash)
{
  khash_t(ht) *h = RHASH_TBL(hash);

  mrb_hash_modify(mrb, hash);
  if (h) kh_clear(ht, mrb, h);
  return hash;
}

#compactObject

call-seq: hsh.compact -> new_hsh

Returns a new hash with the nil values/key pairs removed

h = { a: 1, b: false, c: nil } h.compact #=> { a: 1, b: false } h #=> { a: 1, b: false, c: nil }


127
128
129
130
131
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 127

def compact
  result = self.dup
  result.compact!
  result
end

#compact!Hash

Removes all nil values from the hash. Returns the hash.

h = { a: 1, b: false, c: nil } h.compact! #=> { a: 1, b: false }

Returns:


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'mrbgems/mruby-hash-ext/src/hash-ext.c', line 48

static mrb_value
hash_compact_bang(mrb_state *mrb, mrb_value hash)
{
  khiter_t k;
  khash_t(ht) *h = RHASH_TBL(hash);
  mrb_int n = -1;

  if (!h) return mrb_nil_value();
  for (k = kh_begin(h); k != kh_end(h); k++) {
    if (kh_exist(h, k)) {
      mrb_value val = kh_value(h, k).v;
      khiter_t k2;

      if (mrb_nil_p(val)) {
        kh_del(ht, mrb, h, k);
        n = kh_value(h, k).n;
        for (k2 = kh_begin(h); k2 != kh_end(h); k2++) {
          if (!kh_exist(h, k2)) continue;
          if (kh_value(h, k2).n > n) kh_value(h, k2).n--;
        }
      }
    }
  }
  if (n < 0) return mrb_nil_value();
  return hash;
}

#default(key = nil) ⇒ Object

Returns the default value, the value that would be returned by hsh[key] if key did not exist in hsh. See also Hash::new and Hash#default=.

h = Hash.new #=> {} h.default #=> nil h.default(2) #=> nil

h = Hash.new(“cat”) #=> {} h.default #=> “cat” h.default(2) #=> “cat”

h = Hash.new {|h,k| h[k] = k.to_i*10} #=> {} h.default #=> nil h.default(2) #=> 20

Returns:


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'src/hash.c', line 412

static mrb_value
mrb_hash_default(mrb_state *mrb, mrb_value hash)
{
  mrb_value key;
  mrb_bool given;

  mrb_get_args(mrb, "|o?", &key, &given);
  if (MRB_RHASH_DEFAULT_P(hash)) {
    if (MRB_RHASH_PROCDEFAULT_P(hash)) {
      if (!given) return mrb_nil_value();
      return mrb_funcall(mrb, RHASH_PROCDEFAULT(hash), "call", 2, hash, key);
    }
    else {
      return RHASH_IFNONE(hash);
    }
  }
  return mrb_nil_value();
}

#default=(obj) ⇒ Object

Sets the default value, the value returned for a key that does not exist in the hash. It is not possible to set the default to a Proc that will be executed on each key lookup.

h = { “a” => 100, “b” => 200 } h.default = “Go fish” h[“a”] #=> 100 h[“z”] #=> “Go fish” # This doesn’t do what you might hope… h.default = proc do |hash, key| hash[key] = key + key end h[2] #=> #<Proc:[email protected]:6> h[“cat”] #=> #<Proc:[email protected]:6>

Returns:


452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'src/hash.c', line 452

static mrb_value
mrb_hash_set_default(mrb_state *mrb, mrb_value hash)
{
  mrb_value ifnone;

  mrb_get_args(mrb, "o", &ifnone);
  mrb_hash_modify(mrb, hash);
  mrb_iv_set(mrb, hash, mrb_intern_lit(mrb, "ifnone"), ifnone);
  RHASH(hash)->flags &= ~MRB_HASH_PROC_DEFAULT;
  if (!mrb_nil_p(ifnone)) {
    RHASH(hash)->flags |= MRB_HASH_DEFAULT;
  }
  else {
    RHASH(hash)->flags &= ~MRB_HASH_DEFAULT;
  }
  return ifnone;
}

#default_procObject

If Hash::new was invoked with a block, return that block, otherwise return nil.

h = Hash.new {|h,k| h[k] = k*k } #=> {} p = h.default_proc #=> #<Proc:[email protected]:1> a = [] #=> [] p.call(a, 2) a #=> [nil, nil, 4]

Returns:


486
487
488
489
490
491
492
493
# File 'src/hash.c', line 486

static mrb_value
mrb_hash_default_proc(mrb_state *mrb, mrb_value hash)
{
  if (MRB_RHASH_PROCDEFAULT_P(hash)) {
    return RHASH_PROCDEFAULT(hash);
  }
  return mrb_nil_value();
}

#default_proc=(proc_obj) ⇒ Proc

Sets the default proc to be executed on each key lookup.

h.default_proc = proc do |hash, key| hash[key] = key + key end h[2] #=> 4 h[“cat”] #=> “catcat”

Returns:


508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'src/hash.c', line 508

static mrb_value
mrb_hash_set_default_proc(mrb_state *mrb, mrb_value hash)
{
  mrb_value ifnone;

  mrb_get_args(mrb, "o", &ifnone);
  mrb_hash_modify(mrb, hash);
  mrb_iv_set(mrb, hash, mrb_intern_lit(mrb, "ifnone"), ifnone);
  if (!mrb_nil_p(ifnone)) {
    RHASH(hash)->flags |= MRB_HASH_PROC_DEFAULT;
    RHASH(hash)->flags |= MRB_HASH_DEFAULT;
  }
  else {
    RHASH(hash)->flags &= ~MRB_HASH_DEFAULT;
    RHASH(hash)->flags &= ~MRB_HASH_PROC_DEFAULT;
  }

  return ifnone;
}

#delete(key, &block) ⇒ Object

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


56
57
58
59
60
61
62
# 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(&block) ⇒ Object

call-seq: hsh.delete_if {| key, value | block } -> hsh hsh.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}

189
190
191
192
193
194
195
196
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 189

def delete_if(&block)
  return to_enum :delete_if unless block

  self.each do |k, v|
    self.delete(k) if block.call(k, v)
  end
  self
end

#dig(idx, *args) ⇒ Object

call-seq: hsh.dig(key,…) -> object

Extracts the nested value specified by the sequence of key objects by calling +dig+ at each step, returning +nil+ if any intermediate step is +nil+.


393
394
395
396
397
398
399
400
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 393

def dig(idx,*args)
  n = self[idx]
  if args.size > 0
    n&.dig(*args)
  else
    n
  end
end

#dupObject

15.2.13.4.24


228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'src/hash.c', line 228

static mrb_value
mrb_hash_dup(mrb_state *mrb, mrb_value hash)
{
  struct RHash* ret;
  khash_t(ht) *h, *ret_h;
  khiter_t k, ret_k;
  mrb_value ifnone, vret;

  h = RHASH_TBL(hash);
  ret = (struct RHash*)mrb_obj_alloc(mrb, MRB_TT_HASH, mrb->hash_class);
  ret->ht = kh_init(ht, mrb);

  if (h && kh_size(h) > 0) {
    ret_h = ret->ht;

    for (k = kh_begin(h); k != kh_end(h); k++) {
      if (kh_exist(h, k)) {
        int ai = mrb_gc_arena_save(mrb);
        ret_k = kh_put(ht, mrb, ret_h, KEY(kh_key(h, k)));
        mrb_gc_arena_restore(mrb, ai);
        kh_val(ret_h, ret_k).v = kh_val(h, k).v;
        kh_val(ret_h, ret_k).n = kh_size(ret_h)-1;
      }
    }
  }

  if (MRB_RHASH_DEFAULT_P(hash)) {
    ret->flags |= MRB_HASH_DEFAULT;
  }
  if (MRB_RHASH_PROCDEFAULT_P(hash)) {
    ret->flags |= MRB_HASH_PROC_DEFAULT;
  }
  vret = mrb_obj_value(ret);
  ifnone = RHASH_IFNONE(hash);
  if (!mrb_nil_p(ifnone)) {
      mrb_iv_set(mrb, vret, mrb_intern_lit(mrb, "ifnone"), ifnone);
  }
  return vret;
}

#each(&block) ⇒ Object Also known as: each_pair

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

call-seq: hsh.each {| key, value | block } -> hsh hsh.each_pair {| key, value | block } -> hsh hsh.each -> an_enumerator hsh.each_pair -> an_enumerator

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


86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'mrblib/hash.rb', line 86

def each(&block)
  return to_enum :each unless block

  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

#each_key(&block) ⇒ Object

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

call-seq: hsh.each_key {| key | block } -> hsh hsh.each_key -> an_enumerator

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


119
120
121
122
123
124
# File 'mrblib/hash.rb', line 119

def each_key(&block)
  return to_enum :each_key unless block

  self.keys.each{|k| block.call(k)}
  self
end

#each_value(&block) ⇒ Object

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

call-seq: hsh.each_value {| value | block } -> hsh hsh.each_value -> an_enumerator

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


145
146
147
148
149
150
# File 'mrblib/hash.rb', line 145

def each_value(&block)
  return to_enum :each_value unless block

  self.keys.each{|k| block.call(self[k])}
  self
end

#empty?Boolean

Returns true if hsh contains no key-value pairs.

{}.empty? #=> true

Returns:

  • (Boolean)

Returns:

  • (Boolean)

712
713
714
715
716
717
718
719
# File 'src/hash.c', line 712

MRB_API mrb_value
mrb_hash_empty_p(mrb_state *mrb, mrb_value self)
{
  khash_t(ht) *h = RHASH_TBL(self);

  if (h) return mrb_bool_value(kh_size(h) == 0);
  return mrb_true_value();
}

#eql?(hash) ⇒ Boolean

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

ISO 15.2.13.4.32 (x)

Returns:

  • (Boolean)

33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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, none = NONE, &block) ⇒ Object

call-seq: hsh.fetch(key [, default] ) -> obj hsh.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

161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 161

def fetch(key, none=NONE, &block)
  unless self.key?(key)
    if block
      block.call(key)
    elsif none != NONE
      none
    else
      raise KeyError, "Key not found: #{key.inspect}"
    end
  else
    self[key]
  end
end

#fetch_values(*keys, &block) ⇒ Object

call-seq: hsh.fetch_values(key, …) -> array hsh.fetch_values(key, …) { |key| block } -> array

Returns an array containing the values associated with the given keys but also raises KeyError when one of keys can’t be found. Also see Hash#values_at and Hash#fetch.

h = { “cat” => “feline”, “dog” => “canine”, “cow” => “bovine” }

h.fetch_values(“cow”, “cat”) #=> [“bovine”, “feline”] h.fetch_values(“cow”, “bird”) # raises KeyError h.fetch_values(“cow”, “bird”) { |k| k.upcase } #=> [“bovine”, “BIRD”]


497
498
499
500
501
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 497

def fetch_values(*keys, &block)
  keys.map do |k|
    self.fetch(k, &block)
  end
end

#flatten(level = 1) ⇒ Object

call-seq: hash.flatten -> an_array hash.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"]

214
215
216
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 214

def flatten(level=1)
  self.to_a.flatten(level)
end

#has_key?(key) ⇒ Boolean #include?(key) ⇒ Boolean #key?(key) ⇒ Boolean #member?(key) ⇒ Boolean

Returns true if the given key is present in hsh.

h = { “a” => 100, “b” => 200 } h.has_key?(“a”) #=> true h.has_key?(“z”) #=> false

Overloads:

  • #has_key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #include?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #member?(key) ⇒ Boolean

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'src/hash.c', line 829

static mrb_value
mrb_hash_has_key(mrb_state *mrb, mrb_value hash)
{
  mrb_value key;
  khash_t(ht) *h;
  khiter_t k;

  mrb_get_args(mrb, "o", &key);

  h = RHASH_TBL(hash);
  if (h) {
    k = kh_get(ht, mrb, h, key);
    return mrb_bool_value(k != kh_end(h));
  }
  return mrb_false_value();
}

#has_value?(value) ⇒ Boolean #value?(value) ⇒ Boolean

Returns true if the given value is present for some key in hsh.

h = { “a” => 100, “b” => 200 } h.has_value?(100) #=> true h.has_value?(999) #=> false

Overloads:

  • #has_value?(value) ⇒ Boolean

    Returns:

    • (Boolean)
  • #value?(value) ⇒ Boolean

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
# File 'src/hash.c', line 861

static mrb_value
mrb_hash_has_value(mrb_state *mrb, mrb_value hash)
{
  mrb_value val;
  khash_t(ht) *h;
  khiter_t k;

  mrb_get_args(mrb, "o", &val);
  h = RHASH_TBL(hash);

  if (h) {
    for (k = kh_begin(h); k != kh_end(h); k++) {
      if (!kh_exist(h, k)) continue;

      if (mrb_equal(mrb, kh_value(h, k).v, val)) {
        return mrb_true_value();
      }
    }
  }
  return mrb_false_value();
}

#has_key?(key) ⇒ Boolean #include?(key) ⇒ Boolean #key?(key) ⇒ Boolean #member?(key) ⇒ Boolean

Returns true if the given key is present in hsh.

h = { “a” => 100, “b” => 200 } h.has_key?(“a”) #=> true h.has_key?(“z”) #=> false

Overloads:

  • #has_key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #include?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #member?(key) ⇒ Boolean

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'src/hash.c', line 829

static mrb_value
mrb_hash_has_key(mrb_state *mrb, mrb_value hash)
{
  mrb_value key;
  khash_t(ht) *h;
  khiter_t k;

  mrb_get_args(mrb, "o", &key);

  h = RHASH_TBL(hash);
  if (h) {
    k = kh_get(ht, mrb, h, key);
    return mrb_bool_value(k != kh_end(h));
  }
  return mrb_false_value();
}

#inspectObject Also known as: to_s

ISO 15.2.13.4.30 (x)


207
208
209
210
211
212
213
# File 'mrblib/hash.rb', line 207

def inspect
  begin
    self._inspect
  rescue SystemStackError
    "{...}"
  end
end

#invertObject

call-seq: hsh.invert -> new_hash

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"}

229
230
231
232
233
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 229

def invert
  h = self.class.new
  self.each {|k, v| h[v] = k }
  h
end

#keep_if(&block) ⇒ Object

call-seq: hsh.keep_if {| key, value | block } -> hsh hsh.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.


246
247
248
249
250
251
252
253
254
255
256
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 246

def keep_if(&block)
  return to_enum :keep_if unless block

  keys = []
  self.each do |k, v|
    unless block.call([k, v])
      self.delete(k)
    end
  end
  self
end

#key(val) ⇒ Object

call-seq: hsh.key(value) -> key

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

271
272
273
274
275
276
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 271

def key(val)
  self.each do |k, v|
    return k if v == val
  end
  nil
end

#has_key?(key) ⇒ Boolean #include?(key) ⇒ Boolean #key?(key) ⇒ Boolean #member?(key) ⇒ Boolean

Returns true if the given key is present in hsh.

h = { “a” => 100, “b” => 200 } h.has_key?(“a”) #=> true h.has_key?(“z”) #=> false

Overloads:

  • #has_key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #include?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #member?(key) ⇒ Boolean

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'src/hash.c', line 829

static mrb_value
mrb_hash_has_key(mrb_state *mrb, mrb_value hash)
{
  mrb_value key;
  khash_t(ht) *h;
  khiter_t k;

  mrb_get_args(mrb, "o", &key);

  h = RHASH_TBL(hash);
  if (h) {
    k = kh_get(ht, mrb, h, key);
    return mrb_bool_value(k != kh_end(h));
  }
  return mrb_false_value();
}

#keysArray

Returns a new array populated with the keys from this hash. See also Hash#values.

h = { “a” => 100, “b” => 200, “c” => 300, “d” => 400 } h.keys #=> [“a”, “b”, “c”, “d”]

Returns:


748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'src/hash.c', line 748

MRB_API mrb_value
mrb_hash_keys(mrb_state *mrb, mrb_value hash)
{
  khash_t(ht) *h = RHASH_TBL(hash);
  khiter_t k;
  mrb_int end;
  mrb_value ary;
  mrb_value *p;

  if (!h || kh_size(h) == 0) return mrb_ary_new(mrb);
  ary = mrb_ary_new_capa(mrb, kh_size(h));
  end = kh_size(h)-1;
  mrb_ary_set(mrb, ary, end, mrb_nil_value());
  p = RARRAY_PTR(ary);
  for (k = kh_begin(h); k != kh_end(h); k++) {
    if (kh_exist(h, k)) {
      mrb_value kv = kh_key(h, k);
      mrb_hash_value hv = kh_value(h, k);

      if (hv.n <= end) {
        p[hv.n] = kv;
      }
      else {
        p[end] = kv;
      }
    }
  }
  return ary;
}

#lengthFixnum #sizeFixnum

Returns the number of key-value pairs in the hash.

h = { “d” => 100, “a” => 200, “v” => 300, “e” => 400 } h.length #=> 4 h.delete(“a”) #=> 200 h.length #=> 3

Overloads:


693
694
695
696
697
698
699
700
# File 'src/hash.c', line 693

static mrb_value
mrb_hash_size_m(mrb_state *mrb, mrb_value self)
{
  khash_t(ht) *h = RHASH_TBL(self);

  if (!h) return mrb_fixnum_value(0);
  return mrb_fixnum_value(kh_size(h));
}

#has_key?(key) ⇒ Boolean #include?(key) ⇒ Boolean #key?(key) ⇒ Boolean #member?(key) ⇒ Boolean

Returns true if the given key is present in hsh.

h = { “a” => 100, “b” => 200 } h.has_key?(“a”) #=> true h.has_key?(“z”) #=> false

Overloads:

  • #has_key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #include?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #key?(key) ⇒ Boolean

    Returns:

    • (Boolean)
  • #member?(key) ⇒ Boolean

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'src/hash.c', line 829

static mrb_value
mrb_hash_has_key(mrb_state *mrb, mrb_value hash)
{
  mrb_value key;
  khash_t(ht) *h;
  khiter_t k;

  mrb_get_args(mrb, "o", &key);

  h = RHASH_TBL(hash);
  if (h) {
    k = kh_get(ht, mrb, h, key);
    return mrb_bool_value(k != kh_end(h));
  }
  return mrb_false_value();
}

#merge(other, &block) ⇒ Object

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

Raises:


181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'mrblib/hash.rb', line 181

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, &block) ⇒ Object Also known as: update

call-seq: hsh.merge!(other_hash) -> hsh hsh.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}

Raises:


103
104
105
106
107
108
109
110
111
112
113
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 103

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

#rehashObject

call-seq: hsh.rehash -> hsh

Rebuilds the hash based on the current hash values for each key. If values of key objects have changed since they were inserted, this method will reindex hsh.

h = {"AAA" => "b"}
h.keys[0].chop!
h          #=> {"AA"=>"b"}
h["AA"]    #=> nil
h.rehash   #=> {"AA"=>"b"}
h["AA"]    #=> "b"

338
339
340
341
342
343
344
# File 'mrblib/hash.rb', line 338

def rehash
  h = {}
  self.each{|k,v|
    h[k] = v
  }
  self.replace(h)
end

#reject(&block) ⇒ Object

call-seq: hsh.reject {|key, value| block} -> a_hash hsh.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 Hash#reject returns Hash; ISO says nothing.


258
259
260
261
262
263
264
265
266
267
268
# File 'mrblib/hash.rb', line 258

def reject(&block)
  return to_enum :reject unless block

  h = {}
  self.each{|k,v|
    unless block.call([k, v])
      h[k] = v
    end
  }
  h
end

#reject!(&block) ⇒ Object

call-seq: hsh.reject! {| key, value | block } -> hsh or nil hsh.reject! -> an_enumerator

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

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


227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'mrblib/hash.rb', line 227

def reject!(&block)
  return to_enum :reject! unless block

  keys = []
  self.each{|k,v|
    if block.call([k, v])
      keys.push(k)
    end
  }
  return nil if keys.size == 0
  keys.each{|k|
    self.delete(k)
  }
  self
end

#replace(hash) ⇒ Object Also known as: initialize_copy

Replaces the contents of hsh with the contents of other hash

ISO 15.2.13.4.23

Raises:


156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'mrblib/hash.rb', line 156

def replace(hash)
  raise TypeError, "can't convert argument into Hash" unless hash.respond_to?(:to_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

#select(&block) ⇒ Object

call-seq: hsh.select {|key, value| block} -> a_hash hsh.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 Hash#select returns Hash; ISO says nothing


311
312
313
314
315
316
317
318
319
320
321
# File 'mrblib/hash.rb', line 311

def select(&block)
  return to_enum :select unless block

  h = {}
  self.each{|k,v|
    if block.call([k, v])
      h[k] = v
    end
  }
  h
end

#select!(&block) ⇒ Object

call-seq: hsh.select! {| key, value | block } -> hsh or nil hsh.select! -> an_enumerator

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

1.9 Hash#select! returns Hash; ISO says nothing.


280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'mrblib/hash.rb', line 280

def select!(&block)
  return to_enum :select! unless block

  keys = []
  self.each{|k,v|
    unless block.call([k, v])
      keys.push(k)
    end
  }
  return nil if keys.size == 0
  keys.each{|k|
    self.delete(k)
  }
  self
end

#shiftArray, Object

Removes a key-value pair from hsh and returns it as the two-item array [ key, value ], or the hash’s default value if the hash is empty.

h = { 1 => "a", 2 => "b", 3 => "c" }
h.shift   #=> [1, "a"]
h         #=> {2=>"b", 3=>"c"}

Returns:


596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'src/hash.c', line 596

static mrb_value
mrb_hash_shift(mrb_state *mrb, mrb_value hash)
{
  khash_t(ht) *h = RHASH_TBL(hash);
  khiter_t k;
  mrb_value delKey, delVal;

  mrb_hash_modify(mrb, hash);
  if (h && kh_size(h) > 0) {
    for (k = kh_begin(h); k != kh_end(h); k++) {
      if (!kh_exist(h, k)) continue;

      delKey = kh_key(h, k);
      mrb_gc_protect(mrb, delKey);
      delVal = mrb_hash_delete_key(mrb, hash, delKey);
      mrb_gc_protect(mrb, delVal);

      return mrb_assoc_new(mrb, delKey, delVal);
    }
  }

  if (MRB_RHASH_DEFAULT_P(hash)) {
    if (MRB_RHASH_PROCDEFAULT_P(hash)) {
      return mrb_funcall(mrb, RHASH_PROCDEFAULT(hash), "call", 2, hash, mrb_nil_value());
    }
    else {
      return RHASH_IFNONE(hash);
    }
  }
  return mrb_nil_value();
}

#lengthFixnum #sizeFixnum

Returns the number of key-value pairs in the hash.

h = { “d” => 100, “a” => 200, “v” => 300, “e” => 400 } h.length #=> 4 h.delete(“a”) #=> 200 h.length #=> 3

Overloads:


693
694
695
696
697
698
699
700
# File 'src/hash.c', line 693

static mrb_value
mrb_hash_size_m(mrb_state *mrb, mrb_value self)
{
  khash_t(ht) *h = RHASH_TBL(self);

  if (!h) return mrb_fixnum_value(0);
  return mrb_fixnum_value(kh_size(h));
}

#slice(*keys) ⇒ Hash

Returns a hash containing only the given keys and their values.

h = { a: 100, b: 200, c: 300 } h.slice(:a) #=> :a=>100 h.slice(:b, :c, :d) #=> :c=>300

Returns:


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'mrbgems/mruby-hash-ext/src/hash-ext.c', line 85

static mrb_value
hash_slice(mrb_state *mrb, mrb_value hash)
{
  khash_t(ht) *h = RHASH_TBL(hash);
  mrb_value *argv, result;
  mrb_int argc, i;
  khiter_t k;
  int ai;

  mrb_get_args(mrb, "*", &argv, &argc);
  if (argc == 0 || h == NULL) {
    return mrb_hash_new_capa(mrb, argc);
  }
  result = mrb_hash_new_capa(mrb, argc);
  ai = mrb_gc_arena_save(mrb);
  for (i = 0; i < argc; i++) {
    mrb_value key = argv[i];

    k = kh_get(ht, mrb, h, key);
    if (k != kh_end(h)) {
      mrb_value val = kh_value(h, k).v;

      mrb_hash_set(mrb, result, key, val);
    }
    mrb_gc_arena_restore(mrb, ai);
  }
  return result;
}

#[]=(key) ⇒ Object #store(key, value) ⇒ Object

Element Assignment—Associates the value given by value with the key given by key. key should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen).

h = { "a" => 100, "b" => 200 }
h["a"] = 9
h["c"] = 4
h   #=> {"a"=>9, "b"=>200, "c"=>4}

669
670
671
672
673
674
675
676
677
# File 'src/hash.c', line 669

static mrb_value
mrb_hash_aset(mrb_state *mrb, mrb_value self)
{
  mrb_value key, val;

  mrb_get_args(mrb, "oo", &key, &val);
  mrb_hash_set(mrb, self, key, val);
  return val;
}

#to_hObject

call-seq: hsh.to_h -> hsh or new_hash

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


285
286
287
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 285

def to_h
  self
end

#to_hashHash

Returns +self+.

Returns:


729
730
731
732
733
# File 'src/hash.c', line 729

static mrb_value
mrb_hash_to_hash(mrb_state *mrb, mrb_value hash)
{
  return hash;
}

#to_procObject


478
479
480
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 478

def to_proc
  ->x{self[x]}
end

#transform_keys(&block) ⇒ Object

call-seq: hsh.transform_keys {|key| block } -> new_hash hsh.transform_keys -> an_enumerator

Returns a new hash, with the keys computed from running the block once for each key in the hash, and the values unchanged.

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


412
413
414
415
416
417
418
419
420
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 412

def transform_keys(&block)
  return to_enum :transform_keys unless block
  hash = {}
  self.keys.each do |k|
    new_key = block.call(k)
    hash[new_key] = self[k]
  end
  hash
end

#transform_keys!(&block) ⇒ Object

call-seq: hsh.transform_keys! {|key| block } -> hsh hsh.transform_keys! -> an_enumerator

Invokes the given block once for each key in hsh, replacing it with the new key returned by the block, and then returns hsh.

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


431
432
433
434
435
436
437
438
439
440
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 431

def transform_keys!(&block)
  return to_enum :transform_keys! unless block
  self.keys.each do |k|
    value = self[k]
    new_key = block.call(k)
    self.__delete(k)
    self[new_key] = value
  end
  self
end

#transform_values(&b) ⇒ Object

call-seq: hsh.transform_values {|value| block } -> new_hash hsh.transform_values -> an_enumerator

Returns a new hash with the results of running the block once for every value. This method does not change the keys.

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


452
453
454
455
456
457
458
459
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 452

def transform_values(&b)
  return to_enum :transform_values unless block_given?
  hash = {}
  self.keys.each do |k|
    hash[k] = yield(self[k])
  end
  hash
end

#transform_values!(&b) ⇒ Object

call-seq: hsh.transform_values! {|key| block } -> hsh hsh.transform_values! -> an_enumerator

Invokes the given block once for each value in the hash, replacing with the new value returned by the block, and then returns hsh.

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


470
471
472
473
474
475
476
# File 'mrbgems/mruby-hash-ext/mrblib/hash.rb', line 470

def transform_values!(&b)
  return to_enum :transform_values! unless block_given?
  self.keys.each do |k|
    self[k] = yield(self[k])
  end
  self
end

#has_value?(value) ⇒ Boolean #value?(value) ⇒ Boolean

Returns true if the given value is present for some key in hsh.

h = { “a” => 100, “b” => 200 } h.has_value?(100) #=> true h.has_value?(999) #=> false

Overloads:

  • #has_value?(value) ⇒ Boolean

    Returns:

    • (Boolean)
  • #value?(value) ⇒ Boolean

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
# File 'src/hash.c', line 861

static mrb_value
mrb_hash_has_value(mrb_state *mrb, mrb_value hash)
{
  mrb_value val;
  khash_t(ht) *h;
  khiter_t k;

  mrb_get_args(mrb, "o", &val);
  h = RHASH_TBL(hash);

  if (h) {
    for (k = kh_begin(h); k != kh_end(h); k++) {
      if (!kh_exist(h, k)) continue;

      if (mrb_equal(mrb, kh_value(h, k).v, val)) {
        return mrb_true_value();
      }
    }
  }
  return mrb_false_value();
}

#valuesArray

Returns a new array populated with the values from hsh. See also Hash#keys.

h = { “a” => 100, “b” => 200, “c” => 300 } h.values #=> [100, 200, 300]

Returns:


791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# File 'src/hash.c', line 791

MRB_API mrb_value
mrb_hash_values(mrb_state *mrb, mrb_value hash)
{
  khash_t(ht) *h = RHASH_TBL(hash);
  khiter_t k;
  mrb_value ary;

  if (!h) return mrb_ary_new(mrb);
  ary = mrb_ary_new_capa(mrb, kh_size(h));
  for (k = kh_begin(h); k != kh_end(h); k++) {
    if (kh_exist(h, k)) {
      mrb_hash_value hv = kh_value(h, k);

      mrb_ary_set(mrb, ary, hv.n, hv.v);
    }
  }
  return ary;
}

#values_at(key, ...) ⇒ Array

Return an array containing the values associated with the given keys. Also see Hash.select.

h = { “cat” => “feline”, “dog” => “canine”, “cow” => “bovine” } h.values_at(“cow”, “cat”) #=> [“bovine”, “feline”]

Returns:


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'mrbgems/mruby-hash-ext/src/hash-ext.c', line 22

static mrb_value
hash_values_at(mrb_state *mrb, mrb_value hash)
{
  mrb_value *argv, result;
  mrb_int argc, i;
  int ai;

  mrb_get_args(mrb, "*", &argv, &argc);
  result = mrb_ary_new_capa(mrb, argc);
  ai = mrb_gc_arena_save(mrb);
  for (i = 0; i < argc; i++) {
    mrb_ary_push(mrb, result, mrb_hash_get(mrb, hash, argv[i]));
    mrb_gc_arena_restore(mrb, ai);
  }
  return result;
}