"in" python operator equivalent in ruby


I’m new to ruby and I woud like to know if there is some “in” operator in this language. In python i can do, do for example:

if x in a: print(‘x is in a!’)

I wonder if in ruby there is some equivalent operator.

There is indeed: the include? method. For example:

print('x is in a!') if a.include?(x)
1 Like

And there’s also in keyword in Ruby, just like Python when it comes to iterating over an array using for loops:

ary = %w(apple banana cherry date)
for i in ary do
	print("Hello #{i}!\n")

Or in case of iterating over a range with for loop:

for i in 1..15
	puts i


In python, you can do:
a = 1, 2, 3
1 in a # => True

In Ruby you can use the following methods:

a = 1, 2, 3
a.include?(1)    # => true
a.index(2)        # => 1
[1, 2] & a         # => [1, 2]
[5, 6] & a         # => []
[1, 10].&(a).empty?    # => false
[5, 6].&(a).empty?      # => true

Hope this helps!

1 Like

Thank you for the answer!

Thanks! I’ve already seen the include method. I just wondering if there is something for iteration over arrays.

Not sure what you mean. There are lots of ways to iterate over arrays. Can you be more specific about what you’re looking for?

In Python are used to determine whether a value is of a certain class or type. They are usually used to determine the type of data a certain variable contains.