Skip to content

Commit 4014ebe

Browse files
committed
Implement Hash#choice
1 parent d81b7cd commit 4014ebe

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

hash.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1348,6 +1348,30 @@ rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
13481348
return result;
13491349
}
13501350

1351+
/*
1352+
* call-seq:
1353+
* hsh.choice(key, ...) -> Hash
1354+
*
1355+
* Return a key-value pair associated with given keys.
1356+
*
1357+
* { :a => 1, 2 => "2", "c" => true }.choice(:a, 2) # => { :a => 1, 2 => "2" }
1358+
* { :a => 1, 2 => "2", "c" => true }.choice("c", 10000) # => { "c" => true, 10000 => nil }
1359+
*/
1360+
1361+
VALUE
1362+
rb_hash_choice(int argc, VALUE *argv, VALUE self){
1363+
int i;
1364+
VALUE result, value;
1365+
result = rb_hash_new();
1366+
1367+
for(i=0; i < argc; i++){
1368+
value = rb_hash_aref(self, argv[i]);
1369+
rb_hash_aset(result, argv[i], value);
1370+
}
1371+
1372+
return result;
1373+
}
1374+
13511375
/*
13521376
* call-seq:
13531377
* hsh.fetch_values(key, ...) -> array
@@ -4476,6 +4500,7 @@ Init_Hash(void)
44764500
rb_define_method(rb_cHash, "keys", rb_hash_keys, 0);
44774501
rb_define_method(rb_cHash, "values", rb_hash_values, 0);
44784502
rb_define_method(rb_cHash, "values_at", rb_hash_values_at, -1);
4503+
rb_define_method(rb_cHash, "choice", rb_hash_choice, -1);
44794504
rb_define_method(rb_cHash, "fetch_values", rb_hash_fetch_values, -1);
44804505

44814506
rb_define_method(rb_cHash, "shift", rb_hash_shift, 0);

test/ruby/test_hash.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,17 @@ def test_values_at
572572
assert_equal ['three', nil, 'one', 'nil'], res
573573
end
574574

575+
def test_choice
576+
res = @h.choice()
577+
assert_equal({}, res)
578+
579+
res = @h.choice(1,2)
580+
assert_equal({1 => "one", 2 => "two"}, res)
581+
582+
res = @h.choice(1,2,1000)
583+
assert_equal({1 => "one", 2 => "two", 1000 => nil}, res)
584+
end
585+
575586
def test_fetch_values
576587
res = @h.fetch_values
577588
assert_equal(0, res.length)

0 commit comments

Comments
 (0)