0

I am making a text game and when you get to the final door, it is locked. You need three items (Strings in an array) to pass.

So I'm trying to make an if statement to see if your inventory (which can carry the three items, as well as others) contains these specific three items located anywhere.

array1 = ["key1", "key2", "key3", "sword", "dagger"]
array2 = ["key1", "key2", "key3"]

if array1.include? array2
  puts "it does"
else
  puts "it doesn't"
end

I've tried things like using any and include, but I can't come up with a simple solution on how I would do this as my tests have shown unexpected results.

Thanks.

2
  • @CarySwoveland gave you an excellent answer but have you considered storing inventory in a Hash e.g. inventory = {keys: ["key1","key2","key3"],weapons: ["sword","dagger"]} then it would be as simple as inventory[:keys] == array2. This would also add to in game functionality by classifying things like keys, weapons, and many more items. Commented Dec 11, 2014 at 18:19
  • @engineersmnky - Good idea! I haven't gotten to the hash part of the learning path, so I will definitely check that out, it seems like a better way to go. Also, I made it that in the story, I took out the weapons part, so it solely relies on items. Commented Dec 11, 2014 at 23:39

1 Answer 1

3

You can use array intersection:

array1 = ["key1", "key2", "key3", "sword", "dagger"]
array2 = ["key1", "key2", "key3"]

puts (array1 & array2 == array2) ? "it does" : "it doesn't"
  #=> "it does"

array2 = ["key1", "key2", "cat"]
puts (array1 & array2 == array2) ? "it does" : "it doesn't"
  #=> "it doesn't"

or difference:

puts (array2 - array1).empty? ? "it does" : "it doesn't"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate, I used this method and implemented it. Now they can get through the door with the items, but rejected if they don't. Also I have a bit more array work to do :)

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.