Forum: Ruby newbie to ruby, search an array

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Roger R. (Guest)
on 2008-10-16 14:56
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
Hoesel, Daniël van (Guest)
on 2008-10-16 15:02
(Received via mailing list)
Use: array.include?(value)

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

Regards,

Daniel
Mateusz T. (Guest)
on 2008-10-16 15:03
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
Roger R. (Guest)
on 2008-10-16 15:35
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
Sebastian H. (Guest)
on 2008-10-16 18:39
(Received via mailing list)
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
Robert K. (Guest)
on 2008-10-16 19:16
(Received via mailing list)
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
Roger R. (Guest)
on 2008-10-16 20:00
thanks for the help, much appreciated, got it going
Roger R. (Guest)
on 2008-10-20 17:31
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
This topic is locked and can not be replied to.