1

I am trying to check if variable is in array so I used a solution found here.

The code below works fine if I pass value of tea direct in the include function as per below.

mycheck= ['Soap', 'Tea', 'Sugar'].include? 'Tea'
      if mycheck == true
        print("yes present")
      else
        print("not present")
      end

My issues: My issue if I set value tea to a variable as per code below, it returns false

var_tea = 'Tea'
mycheck= ['Soap', 'Tea', 'Sugar'].include? var_tea
      if mycheck == true
        print("yes present")
      else
        print("not present")
      end

Is there any other alternative way like using is_array(), etc?

halfer
  • 19,824
  • 17
  • 99
  • 186
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
  • Your code is working fine, it's not the issue it may be something else. please cross check it. – Anand Apr 17 '19 at 08:53

2 Answers2

2

I tried these two lines

var_tea = 'Tea'
mycheck = ['Soap', 'Tea', 'Sugar'].include? var_tea

and mycheck is true

My guess is that you obviously don't have that variable in the line above, it's probably coming from a request, and that's not exactly Tea, maybe tea. Try to print var_tea before that check.

puts var_tea.inspect
Ursus
  • 29,643
  • 3
  • 33
  • 50
0

Your code seems right, but you could make it better.

First of all, you're checking if a variable is true. A better way to do it in ruby would be:

if mycheck
  print("yes present")
else
  print("not present")
end

You can also try:

my_check = var_tea.in? ['Soap', 'Tea', 'Sugar']

If you have the same issue, make sure that you double check your code, and that you don't have any my_check= method or something.

Cdalbergue
  • 166
  • 4