Skip to content

Commit

Permalink
Implement Hash#pick
Browse files Browse the repository at this point in the history
  • Loading branch information
baban committed Jun 12, 2017
1 parent a100bf3 commit b3b7f5f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
25 changes: 25 additions & 0 deletions hash.c
Original file line number Diff line number Diff line change
Expand Up @@ -1348,6 +1348,30 @@ rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
return result;
}

/*
* call-seq:
* hsh.pick(key, ...) -> Hash
*
* Return a key-value pair associated with given keys.
*
* { :a => 1, 2 => "2", "c" => true }.pick(:a, 2) # => { :a => 1, 2 => "2" }
* { :a => 1, 2 => "2", "c" => true }.pick("c", 10000) # => { "c" => true, 10000 => nil }
*/

VALUE
rb_hash_pick(int argc, VALUE *argv, VALUE self){
int i;
VALUE result, value;
result = rb_hash_new();

for(i=0; i < argc; i++){
value = rb_hash_aref(self, argv[i]);
rb_hash_aset(result, argv[i], value);
}

return result;
}

/*
* call-seq:
* hsh.fetch_values(key, ...) -> array
Expand Down Expand Up @@ -4485,6 +4509,7 @@ Init_Hash(void)
rb_define_method(rb_cHash, "keys", rb_hash_keys, 0);
rb_define_method(rb_cHash, "values", rb_hash_values, 0);
rb_define_method(rb_cHash, "values_at", rb_hash_values_at, -1);
rb_define_method(rb_cHash, "pick", rb_hash_pick, -1);
rb_define_method(rb_cHash, "fetch_values", rb_hash_fetch_values, -1);

rb_define_method(rb_cHash, "shift", rb_hash_shift, 0);
Expand Down
15 changes: 15 additions & 0 deletions test/ruby/test_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,21 @@ def test_values_at
assert_equal ['three', nil, 'one', 'nil'], res
end

def test_pick
res = @h.pick()
assert_equal({}, res)

res = @h.pick(1,2)
assert_equal({1 => "one", 2 => "two"}, res)

res = @h.pick(1,2,1000)
assert_equal({1 => "one", 2 => "two", 1000 => nil}, res)

h = { a: 10 }
h.default= "default"
assert_equal({1000 => "default"}, h.pick(1000))
end

def test_fetch_values
res = @h.fetch_values
assert_equal(0, res.length)
Expand Down

0 comments on commit b3b7f5f

Please sign in to comment.