how to check if a number is in an array? like `5 in [1, 3, 5]`? in ruby

In Ruby, you can check if a number is present in an array using the include? method. Here's an example:

main.rb
number = 5
array = [1, 3, 5]

if array.include?(number)
  puts "#{number} is in the array"
else
  puts "#{number} is not in the array"
end
139 chars
9 lines

This will output:

main.rb
5 is in the array
18 chars
2 lines

Alternatively, you can also use the include? method directly in a conditional statement like this:

main.rb
number = 5
array = [1, 3, 5]

if number.in?(array)
  puts "#{number} is in the array"
else
  puts "#{number} is not in the array"
end
134 chars
9 lines

This will produce the same output as the previous example.

related categories

gistlibby LogSnag