Reputation: 137
When I used .match and .eql? for string comparison they gave different results
text_from_page = "wrong length (should be 64 characters)"
error_text = "wrong length (should be 64 characters)"
if(text_from_page.eql? error_text)
puts 'matched'
else
puts 'Not matched'
end
The following comparison did not work
if(text_from_page.match error_text)
puts 'matched'
else
puts 'Not matched'
end
Does anyone know the reason for this?
Upvotes: 1
Views: 525
Reputation: 137
@tadman. Thank you. That solved my issue. The ".match" compares the hash values where as the ".eql" compares the stings.
Upvotes: 0
Reputation: 211540
As always, don't just use methods without reading their documentation. There can be important notes.
Here's eql?
:
Two strings are equal if they have the same length and content.
Here's match
:
Converts pattern to a Regexp (if it isn’t already one), then invokes its match method on str. If the second parameter is present, it specifies the position in the string to begin the search.
Note the part about converting. In a regular expression (
and )
, among other characters, have significant meaning. You can't use match
arbitrarily here. It has a very specific function.
You rarely see .eql?
used in actual Ruby code, the convention is simply this:
text_from_page == error_text
The eql?
method is primarily intended for internal use. It comes into play when doing comparisons, and when finding things in a container like an Array or Hash.
Upvotes: 4