I am newbie to Ruby. Are there any better ways to write this:
if (mystring.include? "string1") || (mystring.include? "string2") ||
(mystring.include? "string3")
Syntax: str. include? Parameters: Here, str is the given string. Returns: true if the given string contains the given string or character otherwise false.
Use the any() to check for multiple substrings in a string Within the for loop, check if each substring is in the string using the in keyword syntax substring in string , and append the resulting boolean to a new list.
Two strings or boolean values, are equal if they both have the same length and value. In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.
There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.
Yes, as below :
if %w(string1 string2 string3).any? { |s| my_string.include? s }
# your code
end
Here is the documentation : Enumerable#any?
Passes each element of the collection to the given block. The method returns
true
if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of{ |obj| obj }
that will cause any? to return true if at least one of the collection members is notfalse
ornil
.
Here is another way ( more fastest) :
[13] pry(main)> ary = %w(string1 string2 string3)
=> ["string1", "string2", "string3"]
[14] pry(main)> Regexp.union(ary)
=> /string1|string2|string3/
[15] pry(main)> "abbcstring2"[Regexp.union(ary)]
=> "string2"
[16] pry(main)> "abbcstring"[Regexp.union(ary)]
=> nil
Just read Regexp::union
and str[regexp] → new_str or nil
.
Well, you could always use a regular expression here (risking another jwz quote :)
if mystring =~ /string1|string2|string3/
...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With