Reputation: 45
???? : ??
I was recently in a ruby meetup and this statement was posted as a valid ruby statement. Could someone explain its validity and if possible the versions in which it's valid.
Upvotes: 0
Views: 82
Reputation: 369458
I was recently in a ruby meetup and this statement was posted as a valid ruby statement.
The fact that it was posted as valid doesn't make it so.
Could someone explain its validity
It isn't.
and if possible the versions in which it's valid.
None.
Upvotes: 1
Reputation: 29328
It is likely you are missing a single question mark before the colon: (the white space in not needed however this better mimics your original post)
????? : ??
The above is valid ruby because the interpreter recognizes this statement as:
?? ? ?? : ??
This makes use of the the character literal notation:
character literal notation to represent single character strings, which syntax is a question mark (?) followed by a single character or escape sequence that corresponds to a single codepoint in the script encoding
As well as ternary if [condition] ? true : false
Since every object other than NilClass
or FalseClass
, is considered "truthy" in ruby, the proposed statement breaks down as :
????? : ??
"?" ? "?" : "?"
true ? "?" : "?"
"?"
This will warn about a string literal in a condition because the else branch is unreachable
As for "...the versions in which it's valid" . This syntax appears to have always been valid (although I only tested back to 1.8.7 (2008)). That being said the result you experience today came about in 1.9.
In 1.8.7 the same statement will return 63
the ASCII decimal code point for question mark.
Upvotes: 3
Reputation: 114178
This variation is valid: (and the one you've seen probably works likewise)
????::??
It's interpreted as:
?? ? ?: : ??
With ??
and ?:
being (rarely used) string literals and ?
/ :
being the ternary operator.
It's the same as:
if '?'
':'
else
'?'
end
Out of context, it doesn't do anything useful.
Upvotes: 3