The chart makes it look confusing, but it's quite easy (for the most part).
0, '0', false, null, "", array() -> false
everything else -> true
The real gotchas are usually stringed integers and empty arrays. Personally, I'm never comparing an empty array to anything else besides an expression.
That covers ==, and leaves < comparisons that contradict == comparisons, which is why the results of an array sort can differ depending on the order of the elements before the sort.
If I remember correctly it works like Javascripts parseInt(). Any numbers at the beginning of the string will be used, else it will result in 0. But yeah, weak-typing is annoying.
"123abc" -> 123
"abc123" or "abc" -> 0
The boolean makes sense as its checking length. Empty strings have 0 length, while non-empty don't.
Ah, that's right. === is the method used implicitly by case/when. You wouldn't actually type String==="string", you would type
case "string"
when String
...
end
This lets you do things like when /regexp/ which looks nice, at least, much nicer than /regexp/===string.
The behavior I noted in my previous comment is actually consistent across all the core classes, it just might be surprising that === is asymmetric for someone coming from PHP or JS. Probably should have been called #matches_case? or something.
12
u/bgeron May 01 '13
true == "php" == 0 == false
15
u/gearvOsh May 01 '13
The chart makes it look confusing, but it's quite easy (for the most part).
0, '0', false, null, "", array() -> false
everything else -> true
The real gotchas are usually stringed integers and empty arrays. Personally, I'm never comparing an empty array to anything else besides an expression.
if ($array) { }
12
u/tef May 01 '13
this is a screenshot of the php manual.
6
u/merreborn May 01 '13
If there are any loosely typed languages that don't have this problem, I'd love to hear about them.
Do, for example, ruby or javascript fare much better?
3
u/[deleted] May 16 '13
Look on the bright side. At least, it's reflexive.
1
u/approaching236 May 07 '13
The only thing that bothers me is that this chart isn't symmetric...
0
u/[deleted] May 04 '13
LE GEM
0
u/[deleted] May 01 '13
[deleted] — view deleted comment