Forum: Ruby Search a word in a string

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.
Ada0fa9f326acbba88da65d76f675aca?d=identicon&s=25 Ganesh Ganesh (ganesh_bangalore)
on 2008-11-05 08:09
Is there any ruby supported methods is there for searching a word in a
particular string

For Example "Hi this is for test"
i need to search "Hi"
4c032774402a9fe5ae814b6318c75a60?d=identicon&s=25 Dennie Mans (wouss)
on 2008-11-05 08:49
Ganesh Ganesh wrote:
> Is there any ruby supported methods is there for searching a word in a
> particular string
>
> For Example "Hi this is for test"
> i need to search "Hi"

http://ruby-doc.org/core/classes/String.html

Try it yourself
Ab62466a77199f5f4d400c591fce2ee6?d=identicon&s=25 Vaggelis Typaldos (vtypal)
on 2008-11-05 22:48
Ganesh Ganesh wrote:
> Is there any ruby supported methods is there for searching a word in a
> particular string
>
> For Example "Hi this is for test"
> i need to search "Hi"

Scan is the more appropriate method:
irb(main):001:0> s = "Hi this is for test"
=> "Hi this is for test"
irb(main):002:0> s.scan("Hi")
=> ["Hi"] # creates an array if the required word matches

Otherwise you can use regexp with a conditional:
irb(main):003:0> if s=~ /Hi/
irb(main):004:1>     puts "found"
irb(main):005:1> end
found

include? is another solution:
irb(main):007:0> s.include?("Hi")
=> true
84dc575c33a123789521d53cad0f62ae?d=identicon&s=25 Lloyd Linklater (lloyd)
on 2008-11-06 15:35
Ganesh Ganesh wrote:
> Is there any ruby supported methods is there for searching a word in a
> particular string
>
> For Example "Hi this is for test"
> i need to search "Hi"

Wouss is correct that a simple search would have shown you the answer.
Still, I ask questions here and it is my turn to help with an answer.

With something like this:
"Hi this is for test".index('Hi')

you get a nil if there is no match and the starting point of the string
found if there is one.

e.g.

puts 'string found' unless "Hi this is for test".index('Hi') == nil
This topic is locked and can not be replied to.