0

I am trying to search an Array for a value, if that value is found then return that the value is found and the index at which it was found. If the value is not found then the index returned is -1

array = [1, 2, 3] search_value = gets.chomp array.map.include?(search_value) || -1 if index != -1 puts "Found " + search_value + " at " + index.to_s 

The expected result is Found 2 at 1 instead I receive Found 2 at True, I understand why this is happening but I don't know how to fix it

3 Answers 3

2

You simply can use array.index(element)

Example:

array = [1, 2, 3, 4, 5] array.index(5) || -1 # returns 4 (because 5 is at 4th index) array.index(6) || -1 # returns -1 
Sign up to request clarification or add additional context in comments.

Comments

1

You're looking for Array#index, which returns nil in case the value is not part of the array.

To return -1 when the value is not found:

index = array.index(search_value) || -1 

2 Comments

Why the map? IMO it is useless in this case and actually makes every think slower.
@spickermann you're right, didn't notice it. Just copied the line @HKeys34 had and changed include? to index. Updating it...
0
array = ["1", "2", "3"] search_value = gets.chomp index = array.index(search_value) || -1 puts "Found " + search_value + " at " + index.to_s // Type 2 // Expected output: Found 2 at 1 

I don't know why array = [1, 2, 3] doesn't work correctly but I try array = ["1", "2", "3"] instead it works. Hope someone can explain a little bit.

2 Comments

You need to convert the search_value into Integer with to_i, so you can have them as int the array too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.