Reputation: 4706
Is there a way to check in Ruby whether the string "1:/2"
is contained within a larger string str
, beside iterating over all positions of str
?
Upvotes: 2
Views: 410
Reputation: 18563
You can use the include?
method
str = "wdadwada1:/2wwedaw"
# => "wdadwada1:/2wwedaw"
str.include? "1:/2"
# => true
Upvotes: 6
Reputation: 160551
The simplest and most straight-forward is to simply ask the string if it contains the sub-string:
"...the string 1:/2 is contained..."['1:/2']
# => "1:/2"
!!"...the string 1:/2 is contained..."['1:/2']
# => true
The documentation has the full scoop; Look at the last two examples.
Upvotes: 4
Reputation: 108049
A regular expression will do that.
s =~ /1:\/2/
This will return either nil if s does not contain the string, or the integer position if it does. Since nil is falsy and an integer is truthy, you can use this expression in an if
statement:
if s =~ /1:\/2/
...
end
The regular expression is normally delimited by /
, which is why the slash within the regular expression is escaped as \/
It is possible to use a different delimiter to avoid having to escape the /
:
s =~ %r"1:/2"
You could use other characters than "
with this syntax, if you want.
Upvotes: 5