For ruby where x is an array, how does x.include?(y) check if y is in x? What's the algorithm?
2 Answers
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.
Comments
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
Mark Thomas
@cfarm54 With a large sorted array a binary search would be faster in most cases. 0xcc.net/ruby-bsearch/index.html.en
locoboy
yep, and i assume there are no functions for this in ruby
Mark Thomas
@cfarm54 There are several. In fact I linked to one in my previous comment.
Mark Thomas
As @Marc-AndréLafortune mentioned, the Ruby builtin
Set is even better, as its members are stored as a Hash internally.
O(n). ForO(1), use aSetinstead.