0

For ruby where x is an array, how does x.include?(y) check if y is in x? What's the algorithm?

2

2 Answers 2

6

As an addition to Greg Hewgill's answer, the source code from Ruby 1.9.3 for this method is:

VALUE
rb_ary_includes(VALUE ary, VALUE item)
{
    long i;

    for (i=0; i<RARRAY_LEN(ary); i++) {
        if (rb_equal(RARRAY_PTR(ary)[i], item)) {
            return Qtrue;
        }
    }
    return Qfalse;
}

Thus, as Greg has said, the algorithm is just a linear search through the array.

Sign up to request clarification or add additional context in comments.

Comments

3

Since the array does not have to be sorted, the algorithm cannot be anything better than "look at each element and see if it matches".

4 Comments

@cfarm54 With a large sorted array a binary search would be faster in most cases. 0xcc.net/ruby-bsearch/index.html.en
yep, and i assume there are no functions for this in ruby
@cfarm54 There are several. In fact I linked to one in my previous comment.
As @Marc-AndréLafortune mentioned, the Ruby builtin Set is even better, as its members are stored as a Hash internally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.