I'm a ruby newbie and I'm having trouble understanding why "S" == /[S]/ evaluates to false.
Can anyone explain this? I've also tried
"S" =~ /[S]/
#=> 0 `
"S" =~ /[^S]/
#=> nil
baffling to me
I'm a ruby newbie and I'm having trouble understanding why "S" == /[S]/ evaluates to false.
Can anyone explain this? I've also tried
"S" =~ /[S]/
#=> 0 `
"S" =~ /[^S]/
#=> nil
baffling to me
"S" == /[S]/ is false because == in Ruby doesn't evaluate whether a regexp matches, it just determines whether two objects are equal. The string "S" and the regexp /[S]/ are of course completely different objects and not equal.
=~ (which is a correct way to match a regexp against a string in Ruby) returns the match position. In your first example the match position is the beginning of the string, 0. In the second example there is no match, so =~ returns nil.
"S" == /[S]/
Everything (almost) in Ruby is an object. In this case you are checking for equality between an instance of a String "S" and an instance of a Regexp /[S]/. Therefore, by definition, they are two different objects, hence the expression returns false. Rather than checking for equality with == you should use =~
"S" == /[S]/
When you use a match operator =~ it returns the index of the first match found in a string. Remember that indexing in Ruby starts from 0. In your example the first character in the provided string is matched. The first character is indexed with 0 and that is what the statement returns.
"S" == /[^S]/
By using a caret ^ you are telling Ruby to match anything but what is between square brackets (this is only true in square brackets, ^ is also used to indicate the beginning of a string if used outside []). In your case it is anything but S. Ruby does not find a match and returns nil.