HKeys34
HKeys34

Reputation: 57

Searching Array for a Value

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

Upvotes: 0

Views: 92

Answers (3)

fphilipe
fphilipe

Reputation: 10054

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

Upvotes: 1

Imran Ahmad
Imran Ahmad

Reputation: 2927

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 

Upvotes: 2

Nam V. Do
Nam V. Do

Reputation: 705

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.

Upvotes: 0

Related Questions