tags:

views:

217

answers:

5

Hi guys,

How can I find a value in Array using Ruby 1.8.7 ?

+2  A: 

Hi,

you can use Array.select or Array.index to do that.

andyp
+1  A: 

Use:

myarray.index "valuetoFind"

That will return you the index of the element you want or nil if your array doesn't contain the value.

Wim Hollebrandse
A: 

Like this?

a = [ "a", "b", "c", "d", "e" ]
a[2] +  a[0] + a[1]    #=> "cab"
a[6]                   #=> nil
a[1, 2]                #=> [ "b", "c" ]
a[1..3]                #=> [ "b", "c", "d" ]
a[4..7]                #=> [ "e" ]
a[6..10]               #=> nil
a[-3, 3]               #=> [ "c", "d", "e" ]
# special cases
a[5]                   #=> nil
a[5, 1]                #=> []
a[5..10]               #=> []

or like this?

a = [ "a", "b", "c" ]
a.index("b")   #=> 1
a.index("z")   #=> nil

See the manual.

Ewan Todd
+4  A: 

I'm guessing that you're trying to find if a certain value exists inside the array, and if that's the case, you can use Array#include?(value):

a = [1,2,3,4,5]
a.include?(3)   # => true
a.include?(9)   # => false

If you mean something else, check the Ruby Array API

Mark Westling
A: 

Thanks for replies.

I did like this:

puts 'find' if array.include?(value)
Lucas Renan