public Method

Array.assoc(p1)

array.assoc(obj)     an_array  or  nil

Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches (that is, the first associated array), or nil if no match is found. See also Array#rassoc.

s1 = [ "colors", "red", "blue", "green" ]
s2 = [ "letters", "a", "b", "c" ]
s3 = "foo"
a  = [ s1, s2, s3 ]
a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
a.assoc("foo")      #=> nil

Source Code

/* 
*  call-seq:
*     array.assoc(obj)   ->  an_array  or  nil
*
*  Searches through an array whose elements are also arrays
*  comparing _obj_ with the first element of each contained array
*  using obj.==.
*  Returns the first contained array that matches (that
*  is, the first associated array),
*  or +nil+ if no match is found.
*  See also <code>Array#rassoc</code>.
*
*     s1 = [ "colors", "red", "blue", "green" ]
*     s2 = [ "letters", "a", "b", "c" ]
*     s3 = "foo"
*     a  = [ s1, s2, s3 ]
*     a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
*     a.assoc("foo")      #=> nil
*/

VALUE
rb_ary_assoc(ary, key)
   VALUE ary, key;
{
   long i;
   VALUE v;

   for (i = 0; i < RARRAY(ary)->len; ++i) {
       v = RARRAY(ary)->ptr[i];
       if (TYPE(v) == T_ARRAY &&
           RARRAY(v)->len > 0 &&
           rb_equal(RARRAY(v)->ptr[0], key))
           return v;
   }
   return Qnil;
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.