1

Array#include? provides only a weaker information than what Array#index provides, i.e., when Array#index returns nil, the corresponding method call with Array#include? will return false, and when Array#index returns an integer, Array#include? returns true. Furthermore, comparing the two indicates that there is no significant difference in speed; rather Array#index often shows a better result than Array#include?:

a = %w[boo zoo foo bar]

t = Time.now
10000.times do
  a.include?("foo")
end
puts Time.now - t # => 0.005626235

t = Time.now
10000.times do
  a.index("foo")
end
puts Time.now - t # => 0.003683945

Then, what is the purpose of Array#include?? Can't all code using it be rewritten using Array#index?

4
  • Related: stackoverflow.com/questions/25779451/… Commented Sep 11, 2014 at 6:15
  • Your linked question answers the performance issues, but one reason that Array#include? is present is because it is inherited from Enumerable. Commented Sep 11, 2014 at 6:18
  • @Sparhawk Right. But Array could have overwritten include? with its current index functionality. That would have made it simpler (except for the trickiness of ? used for non-boolean). Commented Sep 11, 2014 at 6:24
  • 1
    I guess if there's not a strong argument to change the behaviour, then it'd be best to keep the inherited behaviour for consistency with other enumerables. Not necessarily very convincing, I know, but perhaps the argument for consistency with ?s suggests a similar thought process. Commented Sep 11, 2014 at 6:32

1 Answer 1

3

I know this isn't an official reason, but I can think of a few things:

  • Clarity: as a name, include? makes more sense at first sight, and also allows easy visual confirmation of code correctness by identifying itself as a boolean predicate. This follows the concept of making wrong code look wrong (see http://www.joelonsoftware.com/articles/Wrong.html)
  • Good typing: If all you want is a boolean value for a boolean check, making that a number could lead to bugs
  • Cleanliness: Isn't it nicer to see a printed output of "true" rather than going back to C and having no boolean to speak of?
Sign up to request clarification or add additional context in comments.

4 Comments

@sawa: In C, there is no boolean type. 0 is false, everything else is true. People started doing all sorts of clever tricks using integers as booleans, and vice versa, and multiplying them, and all that, and it just turns into a mess.
Technically C does have a boolean type. Unless by "C" you mean "whatever old version of C that MS supports".
@muistooshort: What is it? I've never seen it.
It is part of C99 but you have to #include <stdbool.h> to use it.

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.