This question already has answers here:
How to compare strings ignoring the case
(5 answers)
Closed 7 years ago.
I want to test 2 strings for equality in Ruby in a case insensitive manner.
In languages, such as Fantom, you simply write:
string1.equalsIgnoreCase(string2)
What's the idiomatic way to do this in Ruby?
You can use casecmp
"Test".casecmp("teST")
=> 0
"Test".casecmp("teST2")
=> -1
So to test for equality, you can do:
if str.casecmp(str2).zero?
# strings are equal
end
Though there is casecmp:
0 == s1.casecmp(s2) # strings equal
I personally prefer
s1.downcase == s2.downcase
You can convert the strings to lowercase and then compare
a.downcase == b.downcase
Or, if you prefer, to uppercase
a.upcase == b.upcase
You can use String#match method :
s = "Test"
s.match(/teST/i) # => #<MatchData "Test">
s.match(/teST2/i) # => nil
Remember in Ruby all objects are has the truth value, except nil and false. So you can use this trick also to perform conditional testing.
Related
This question already has answers here:
Check whether a string contains one of multiple substrings
(8 answers)
Closed 6 years ago.
i've written a few lines of code like this :
if( (user_input.include?('string_a') ||
(user_input.include? ('string_b')) ||
(user_input.include?('string_c')) )
&&
user_input.include?('string_d_keyword'))
....
end # if
is there any function which can simplify the "multiple or string match" by taking multiple arguments and look like this ?
if( (user_input.multi_include_or?('string_a','string_b','string_c'))
&& (user_input.include?('string_d_keyword')))
.....
end # if
i hope to do these all in a single line and so i've leave out the option of "case when".
Thanks~
You can do a regex match using | (or):
if user_input.match? /string_a|string_b|string_c|string_d_keyword/
…
end
If your strings are in an array you can use Regexp.union to convert them to the corresponding regex:
if user_input.match? Regexp.union(strings)
…
end
Use an array and any?
> user_input = "string_a"
=> "string_a"
> ["asd","string_a"].any? {|a| user_input.include? a}
=> true
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose I have a list of characters [a,b,c] and I want to write a regular expression such that
any string is accepted if it has all the elements in the character list at-least once and the characters can appear in any order in the string.
Example of accepted strings
abc, aabbbc, bbaac, cab
Example of strings not accepteed
aaabb, bab, caa, aacd, deeff
Sets are much more suited for this purpose than regular expressions. What you're really trying to do is find out if (a, b, c) is a valid subset of your various strings. Here's an example of how to do that in Ruby:
> require "set"
=> true
> reference = Set.new("abc".split(""))
=> #<Set: {"a", "b", "c"}>
> test1 = Set.new("aabbbc".split(""))
=> #<Set: {"a", "b", "c"}>
> test2 = Set.new("caa".split(""))
=> #<Set: {"c", "a"}>
> reference.subset? test1
=> true
> reference.subset? test2
=> false
Consider this before reading on: regexes are not always the best way to solve a problem. If you are considering a regex but it's not obvious or easy to proceed, you may want to stop and consider if there is an easy non-regex solution handy.
I don't know what your specific situation is or why you think you need regex, so I'll assume you already know the above and answer your question as-is.
Based on the documentation, I beleive that Ruby supports positive lookaheads (also known as zero-width assertions). Being primarily a .NET programmer, I don't know Ruby well enough to say whether or not it supports non-fixed-length lookaheads (it's not found in all regex flavors), but if it does then you can easily apply three different lookaheads at the beginning of your expression to find each of the patterns or characters you need:
^(?=.*a)(?=.*b)(?=.*c).*
This will fail if any one of the lookaheads does not pass. This approach is potentially extremely powerful because you can have complex sub expressions in your lookahead. For example:
^(?=.*a[bc]{2})(?=.*-\d)(?=.*#.{3}%).*
will test that the input contains an a follwed by two characters which are each either a b or a c, a - followed by any digit and a # followed by any three characters followed by a %, in any particular order. So the following strings would pass:
#acb%-9
#-22%abb
This kind of complex pattern matching is difficult to succinctly duplicate.
To address this comment:
No there cannot be... so abcd is not accepted
You can use a negative lookahead to ensure that characters other than the desired characters are not present in the input:
^(?=.*a)(?=.*b)(?=.*c)(?!.*[^abc]).*
(As noted by Gene, the .* at the end is not necessary... I probably should have mentioned that. It's just there in case you actually want to select the text)
def acceptable? s
s =~ /(?=.*a)(?=.*b)(?=.*c)/
end
acceptable? 'abc' # => 0
acceptable? 'aabbbc' # => 0
acceptable? 'bbaac' # => 0
acceptable? 'cab' # => 0
acceptable? 'aaabb' # => nil
acceptable? 'bab' # => nil
acceptable? 'caa' # => nil
acceptable? 'aacd' # => nil
acceptable? 'deeff' # => nil
acceptable? 'abcd' # => 0
A regex that matches only the defined characters could be this:
(?=[bc]*a)(?=[ac]*b)(?=[ab]*c)[abc]*
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the colon operator in Ruby?
While learning Ruby I've come across the ":" operator on occasion. Usually I see it in the form of
:symbol => value
what does it mean?
It just indicates a that it is a symbol instead of a string. In ruby, it is common to use symbols instead of strings.
{:foo => value}
{'foo' => value}
It's basically a short-hand way of expressing a string. It can not contain spaces as you can imagine so symbols usually use underscores.
Try this on your own:
foo = :bar
foo.to_s # means to string
baz = 'goo'
baz.to_sym # means to symbol
This question already has answers here:
What is the "=~" operator in Ruby?
(7 answers)
Closed 8 years ago.
In ruby, I read some of the operators, but I couldn't find =~. What is =~ for, or what does it mean? The program that I saw has
regexs = (/\d+/)
a = somestring
if a =~ regexs
I think it was comparing if somestring equal to digits but, is there any other usage, and what is the proper definition of the =~ operator?
The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.
/mi/ =~ "hi mike" # => 3
"hi mike" =~ /mi/ # => 3
"mike" =~ /ruby/ # => nil
You can place the string/regex on either side of the operator as you can see above.
This operator matches strings against regular expressions.
s = 'how now brown cow'
s =~ /cow/ # => 14
s =~ /now/ # => 4
s =~ /cat/ # => nil
If the String matches the expression, the operator returns the offset, and if it doesn't, it returns nil. It's slightly more complicated than that: see documentation here; it's a method in the String class.
=~ is an operator for matching regular expressions, that will return the index of the start of the match (or nil if there is no match).
See here for the documentation.
Does Ruby have a some_string.starts_with("abc") method that's built in?
It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. On Rails you can use the alias String#starts_with? (note the plural - and note that this method is deprecated). Personally, I'd prefer String#starts_with? over the actual String#start_with?
Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.
You could always use a regular expression though:
if SomeString.match(/^abc/)
# SomeString starts with abc
^ means "start of string" in regular expressions
If this is for a non-Rails project, I'd use String#index:
"foobar".index("foo") == 0 # => true
You can use String =~ Regex. It returns position of full regex match in string.
irb> ("abc" =~ %r"abc") == 0
=> true
irb> ("aabc" =~ %r"abc") == 0
=> false