Newbie to ruby, search an array

hi, im fairly new to ruby and cud do with some help

is there an easy way to search an array to see if it contains a desired
value

thanks

e.g. if @joe contains ‘bloggs’ return true and array location

thanks

Chris Ashton wrote:

hi, im fairly new to ruby and cud do with some help

is there an easy way to search an array to see if it contains a desired
value

thanks

e.g. if @joe contains ‘bloggs’ return true and array location

thanks

Try this:

tab = [“frogs”,“mugs”,“bloggs”]
tab.index “bloggs” #=> returns index or nil if not found

Use: array.include?(value)

http://www.ruby-doc.org/core/classes/Array.html#M002226

Regards,

Daniel

thanks for the help, i really appreciate it, worked a treat

I also need to do this:

array[count + 1]

array[count] returns x but array[count + 1] returns nil when i should be
y

am i totally wrong or is it something else?

thanks

On 16.10.2008 13:35, Chris Ashton wrote:

thanks for the help, i really appreciate it, worked a treat

I also need to do this:

array[count + 1]

array[count] returns x but array[count + 1] returns nil when i should be
y

am i totally wrong or is it something else?

Depends on count and the size of the Array. Either count is array.size

  • 1 in which case array[count + 1] points after the last element. Or
    your array contains nil at that position.

irb(main):001:0> a=[1,2,3]
=> [1, 2, 3]
irb(main):002:0> a.size
=> 3
irb(main):003:0> a[a.size]
=> nil
irb(main):004:0> a[0]
=> 1
irb(main):005:0> a[1]
=> 2
irb(main):006:0> a[2]
=> 3
irb(main):007:0> a[3]
=> nil
irb(main):008:0>

Cheers

robert

thanks for the help, much appreciated, got it going

hi ive changed the original array to a nested one and the tab.index no
longer works is there a way to search and and the index still

thanks for any help

Chris Ashton wrote:

array[count] returns x but array[count + 1] returns nil when i should be
y

am i totally wrong or is it something else?

Works here:

array=[“x”,“y”]
=> [“x”, “y”]

count=0
=> 0

array[count]
=> “x”

array[count+1]
=> “y”

If array[count+1] does not return y for you that simply means, that y is
not
the value following x in your array.

HTH,
Sebastian