Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Check condition if a string include multi-different strings?

I am newbie to Ruby. Are there any better ways to write this:

if (mystring.include? "string1") || (mystring.include? "string2") ||
   (mystring.include? "string3")
like image 787
Kuroun Avatar asked May 16 '14 06:05

Kuroun


People also ask

How do you check if a string contains another string in Ruby?

Syntax: str. include? Parameters: Here, str is the given string. Returns: true if the given string contains the given string or character otherwise false.

How do I check if a string contains multiple substrings?

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.

How do you compare two strings in Ruby?

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.

Where do I find substrings in Ruby?

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.


2 Answers

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 not false or nil.

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 .

like image 82
Arup Rakshit Avatar answered Oct 30 '22 10:10

Arup Rakshit


Well, you could always use a regular expression here (risking another jwz quote :)

if mystring =~ /string1|string2|string3/
  ...
end
like image 44
nimrodm Avatar answered Oct 30 '22 10:10

nimrodm