3

I come from the Java world so I was shocked to discover that arrays (http://ruby-doc.org/core/classes/Array.html) does not hava a method contains(object) returning bool.

What is the good way - the Ruby way - of doing that ?

7
  • 3
    You'll find that most methods are named differently. :) Commented Nov 4, 2010 at 12:30
  • 4
    You might actually want to read documentation before posting questions like this, otherwise you end up looking stupid and/or lazy. Especially if you are going to link to the documentation in the question. Commented Nov 4, 2010 at 13:26
  • 3
    I ctrl-fed the page with 'contains', 'bool' (to get methods by return type), 'has' ... no luck. Sorry if I disturbed you in your peace Paul Leader. Commented Nov 4, 2010 at 14:25
  • 1
    If that's all you did before posting to SO then it makes you look lazy (hence why your question is rated 0). I'm just suggesting that you might learn rather more if you actually read the docs. In the time it takes to post a question here you could have read most of the Array class documentation, certainly the list of methods right at the top. If I started coding in Java I would not expect every class method to be called the same, and to be able to just ctrl-f for a couple of terms and assume that finding nothing indicates no such thing exists and then be "shocked" at the absence. Commented Nov 4, 2010 at 15:59
  • 2
    Paul: Relax. The answers are often obvious; that doesn't mean we're idiots. Commented Nov 4, 2010 at 20:33

4 Answers 4

7

array.include?(obj) → true or false

Returns true if the given object is present in self (that is, if any object == anObject), false otherwise.

a = [ "a", "b", "c" ]
a.include?("b")   #=> true
a.include?("z")   #=> false

This, from the Array class documentation:

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

Comments

6
[1,2,3].include? 2
=> true

Comments

1
ruby-1.9.2-p0 > [1,2,3].include? 3
 => true 

ruby-1.9.2-p0 > [1,2,3].include? 33
 => false 

3 Comments

did everybody read the question wrong at first... i thought it was "to check if an object is an array"
Yep, so did I. Weird, the title is perfectly correct, but my brain skipped the "in".
could it be while we were typing the answer, the author changed the question.... so question has timestamp which is earlier than our answers, so won't show revision
0

You can do this:

Array.index("ITEM")

if the result is != de nil the element exists.

Regards.

Comments

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.