[270] | 1 | /*
|
---|
| 2 | ** hash.c - Hash class
|
---|
| 3 | **
|
---|
| 4 | ** See Copyright Notice in mruby.h
|
---|
| 5 | */
|
---|
| 6 |
|
---|
[331] | 7 | #include <mruby.h>
|
---|
| 8 | #include <mruby/array.h>
|
---|
| 9 | #include <mruby/hash.h>
|
---|
[270] | 10 |
|
---|
| 11 | /*
|
---|
| 12 | * call-seq:
|
---|
| 13 | * hsh.values_at(key, ...) -> array
|
---|
| 14 | *
|
---|
| 15 | * Return an array containing the values associated with the given keys.
|
---|
| 16 | * Also see <code>Hash.select</code>.
|
---|
| 17 | *
|
---|
| 18 | * h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
|
---|
| 19 | * h.values_at("cow", "cat") #=> ["bovine", "feline"]
|
---|
| 20 | */
|
---|
| 21 |
|
---|
| 22 | static mrb_value
|
---|
| 23 | hash_values_at(mrb_state *mrb, mrb_value hash)
|
---|
| 24 | {
|
---|
| 25 | mrb_value *argv, result;
|
---|
| 26 | mrb_int argc, i;
|
---|
| 27 | int ai;
|
---|
| 28 |
|
---|
| 29 | mrb_get_args(mrb, "*", &argv, &argc);
|
---|
| 30 | result = mrb_ary_new_capa(mrb, argc);
|
---|
| 31 | ai = mrb_gc_arena_save(mrb);
|
---|
| 32 | for (i = 0; i < argc; i++) {
|
---|
| 33 | mrb_ary_push(mrb, result, mrb_hash_get(mrb, hash, argv[i]));
|
---|
| 34 | mrb_gc_arena_restore(mrb, ai);
|
---|
| 35 | }
|
---|
| 36 | return result;
|
---|
| 37 | }
|
---|
| 38 |
|
---|
[439] | 39 | /*
|
---|
| 40 | * call-seq:
|
---|
| 41 | * hsh.slice(*keys) -> a_hash
|
---|
| 42 | *
|
---|
| 43 | * Returns a hash containing only the given keys and their values.
|
---|
| 44 | *
|
---|
| 45 | * h = { a: 100, b: 200, c: 300 }
|
---|
| 46 | * h.slice(:a) #=> {:a=>100}
|
---|
| 47 | * h.slice(:b, :c, :d) #=> {:b=>200, :c=>300}
|
---|
| 48 | */
|
---|
| 49 | static mrb_value
|
---|
| 50 | hash_slice(mrb_state *mrb, mrb_value hash)
|
---|
| 51 | {
|
---|
| 52 | mrb_value *argv, result;
|
---|
| 53 | mrb_int argc, i;
|
---|
| 54 |
|
---|
| 55 | mrb_get_args(mrb, "*", &argv, &argc);
|
---|
| 56 | result = mrb_hash_new_capa(mrb, argc);
|
---|
| 57 | if (argc == 0) return result; /* empty hash */
|
---|
| 58 | for (i = 0; i < argc; i++) {
|
---|
| 59 | mrb_value key = argv[i];
|
---|
| 60 | mrb_value val;
|
---|
| 61 |
|
---|
| 62 | val = mrb_hash_fetch(mrb, hash, key, mrb_undef_value());
|
---|
| 63 | if (!mrb_undef_p(val)) {
|
---|
| 64 | mrb_hash_set(mrb, result, key, val);
|
---|
| 65 | }
|
---|
| 66 | }
|
---|
| 67 | return result;
|
---|
| 68 | }
|
---|
| 69 |
|
---|
[270] | 70 | void
|
---|
| 71 | mrb_mruby_hash_ext_gem_init(mrb_state *mrb)
|
---|
| 72 | {
|
---|
| 73 | struct RClass *h;
|
---|
| 74 |
|
---|
| 75 | h = mrb->hash_class;
|
---|
| 76 | mrb_define_method(mrb, h, "values_at", hash_values_at, MRB_ARGS_ANY());
|
---|
[439] | 77 | mrb_define_method(mrb, h, "slice", hash_slice, MRB_ARGS_ANY());
|
---|
[270] | 78 | }
|
---|
| 79 |
|
---|
| 80 | void
|
---|
| 81 | mrb_mruby_hash_ext_gem_final(mrb_state *mrb)
|
---|
| 82 | {
|
---|
| 83 | }
|
---|