0

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

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107

2 Answers2

3

"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.

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
  • How would I get "S" =~ /[S]/ #=> 0 to return true instead? Also I thought the ^ character means starting charcter – user3684134 May 28 '14 at 15:46
  • 0 is what Ruby calls "truthy" -- it is treated as true in conditionals and such. If you really need to turn it in to boolean true, do `!! ("S" =~ /[S]/)`. Regarding ^, at the beginning of a regexp it means the beginning of the matched string, but inside [] it means "not the following character". – Dave Schweisguth May 28 '14 at 19:05
1
"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.

hp4k
  • 356
  • 2
  • 9