000_ruby_hash_keys_of.patch

Sambasiva Suda, 03/27/2012 01:38 AM

Download (2.36 KB)

View differences:

ChangeLog (working copy)
1
Mon Mar 27 01:20:05 2012  Sambasiva Rao Suda  <sambasivarao@gmail.org>
2

  
3
	* hash.c (rb_hash_keys_of): Adding new method Hash#keys_of(value),
4
	which will return array having all the keys of the given value.  
5
	[ruby-dev:45310][Feature #6118]
6

  
1 7
Mon Mar 26 23:43:04 2012  Shugo Maeda  <shugo@ruby-lang.org>
2 8

  
3 9
	* lib/net/ftp.rb (parse227, parse228, parse229): don't use $~.
hash.c (working copy)
750 750
    return args[1];
751 751
}
752 752

  
753
static int
754
keys_of_i(VALUE key, VALUE value, VALUE ary)
755
{
756
    VALUE arg = rb_ary_entry(ary, 0);
757

  
758
    if (rb_equal(value, arg)) {
759
      rb_ary_push(ary, key);
760
    }
761
    return ST_CONTINUE;
762
}
763

  
764
/*
765
 *  call-seq:
766
 *     hsh.keys_of(value)    -> [key]
767
 *
768
 *  Returns the keys of a given value. If the value is
769
 *  not found, returns <code>[]</code>.
770
 *
771
 *     h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300}
772
 *     h.key(200)   #=> ["b"]
773
 *     h.key(300)   #=> ["c", "d"]
774
 *     h.key(999)   #=> []
775
 *
776
 */
777

  
778
static VALUE
779
rb_hash_keys_of(VALUE hash, VALUE value)
780
{
781
    VALUE ary;
782

  
783
    ary = rb_ary_new();
784

  
785
    rb_ary_push(ary, value);
786

  
787
    rb_hash_foreach(hash, keys_of_i, ary);
788

  
789
    rb_ary_shift(ary);
790

  
791
    return ary;
792
}
793

  
753 794
/* :nodoc: */
754 795
static VALUE
755 796
rb_hash_index(VALUE hash, VALUE value)
test/ruby/test_hash.rb (working copy)
79 79
  def setup
80 80
    @cls = Hash
81 81
    @h = @cls[
82
      1 => 'one', 2 => 'two', 3 => 'three',
82
      1 => 'one', 2 => 'two', 3 => 'three', 4 => 'two'
83 83
      self => 'self', true => 'true', nil => 'nil',
84 84
      'nil' => nil
85 85
    ]
......
422 422
    assert_equal(nil,   @cls[].key('gumby'))
423 423
  end
424 424

  
425
  def test_keys_of
426
    assert_equal([1],     @h.keys_of('one'))
427
    assert_equal([2, 4],  @h.keys_of('two'))
428
    assert_equal([],   @h.keys_of('nil'))
429
    assert_equal([],   @h.keys_of('gumby'))
430
    assert_equal([],   @cls[].keys_of('gumby'))
431
  end
432

  
425 433
  def test_values_at
426 434
    res = @h.values_at('dog', 'cat', 'horse')
427 435
    assert(res.length == 3)