Project

General

Profile

Feature #6118 » 000_ruby_hash_keys_of.patch

ssuda (Sambasiva Suda), 03/27/2012 01:44 AM

View differences:

ChangeLog (working copy)
Mon Mar 27 01:20:05 2012 Sambasiva Rao Suda <sambasivarao@gmail.org>
* hash.c (rb_hash_keys_of): Adding new method Hash#keys_of(value),
which will return array having all the keys of the given value.
[ruby-dev:45310][Feature #6118]
Mon Mar 26 23:43:04 2012 Shugo Maeda <shugo@ruby-lang.org>
* lib/net/ftp.rb (parse227, parse228, parse229): don't use $~.
hash.c (working copy)
return args[1];
}
static int
keys_of_i(VALUE key, VALUE value, VALUE ary)
{
VALUE arg = rb_ary_entry(ary, 0);
if (rb_equal(value, arg)) {
rb_ary_push(ary, key);
}
return ST_CONTINUE;
}
/*
* call-seq:
* hsh.keys_of(value) -> [key]
*
* Returns the keys of a given value. If the value is
* not found, returns <code>[]</code>.
*
* h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300}
* h.key(200) #=> ["b"]
* h.key(300) #=> ["c", "d"]
* h.key(999) #=> []
*
*/
static VALUE
rb_hash_keys_of(VALUE hash, VALUE value)
{
VALUE ary;
ary = rb_ary_new();
rb_ary_push(ary, value);
rb_hash_foreach(hash, keys_of_i, ary);
rb_ary_shift(ary);
return ary;
}
/* :nodoc: */
static VALUE
rb_hash_index(VALUE hash, VALUE value)
test/ruby/test_hash.rb (working copy)
def setup
@cls = Hash
@h = @cls[
1 => 'one', 2 => 'two', 3 => 'three',
1 => 'one', 2 => 'two', 3 => 'three', 4 => 'two',
self => 'self', true => 'true', nil => 'nil',
'nil' => nil
]
......
assert_equal(nil, @cls[].key('gumby'))
end
def test_keys_of
assert_equal([1], @h.keys_of('one'))
assert_equal([2, 4], @h.keys_of('two'))
assert_equal([], @h.keys_of('nil'))
assert_equal([], @h.keys_of('gumby'))
assert_equal([], @cls[].keys_of('gumby'))
end
def test_values_at
res = @h.values_at('dog', 'cat', 'horse')
assert(res.length == 3)
(2-2/2)