18

In python I can use this to check if the element in list a:

>>> a = range(10)
>>> 5 in a
True
>>> 16 in a
False

How this can be done in Ruby?

1

2 Answers 2

27

Use the include?() method:

(1..10).include?(5) #=>true
(1..10).include?(16) #=>false

EDIT: (1..10) is Range in Ruby , in the case you want an Array(list) :

(1..10).to_a #=> [1,2,3,4,5,6,7,8,9,10]
Sign up to request clarification or add additional context in comments.

2 Comments

So this is like index() methods that return nil(false) or index(true)?
Index works only on Array but not on Range. !(1..10).to_a.index(5).nil? equals (1..10).include?(5). Obviously, latter is better.
10

Range has the === method, which checks whether the argument is part of the range.

You use it like this:

(1..10) === 5  #=> true
(1..10) === 15 #=> false

or as you wrote it:

a= (1..10)
a === 5  #=> true
a === 16 #=> false

You must be sure the values of the range and the value you are testing are of compatible type, otherwise an Exception will be thrown.

(2.718..3.141) === 3 #=> true
(23..42) === "foo"   # raises exception
  • This is done in O(1), as Range#===(value) only compares value with Range#first and Range#last.
  • If you first call Range#to_a and then Array#include?, it runs in O(n), as Range#to_a, needs to fill an array with n elements, and Array#include? needs to search through the n elements again.

If you want to see the difference, open irb and type:

(1..10**9) === 5            #=> true
(1..10**9).to_a.include?(5) # wait some time until your computer is out of ram and freezess

3 Comments

This only applies to ranges, the OP asked for lists (and used range only as an example of a list)
he wrote list list but used a Range in his example, so I think he want's a range. It seems as there is no native way in Python to create a range which is not a list. (but I must point out, I am no python expert, so my assumption may be wrong)
In python, there's no range type. So range(10) is to generated [0,1,2,3,4,5,6,7,8,9] list that's (0..9) in ruby (for precisely, it's xrange(10) that's generator which yield value only when you want it). For this case, I didn't notice which type is it before because I used "gets.split.each". Btw, this's a very nice answer!

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.