问题
I have two bits of code that, as far as I understand Ruby, should function identically. Both would sit within the same initialize method:
class TicTacToePlayer
def initialize(player_type = { human: true })
# Here
end
end
The first code is a standard if/else statement:
if player_type[:human]
extend Human
else
extend Joshua
end
The second is just the above as a ternary operator:
player_type[:human] ? extend Human : extend Joshua
...
I would expect both to function identically, but whereas the first operates smoothly, the second returns the following error:
syntax error, unexpected tCONSTANT, expecting keyword_do or '{' or '(' ...yer_type[:human] ? extend Human : extend Joshua # ternary op...
Why the difference?
回答1:
Use parentheses for the function calls
player_type[:human] ? extend(Human) : extend(Joshua)
回答2:
As an alternative to using parentheses like @mtm's answer, you can also write it like this:
extend player_type[:human] ? Human : Joshua
来源:https://stackoverflow.com/questions/25328481/why-does-the-ruby-ternary-operator-not-allow-extending-and-similar