为什么Ruby三元运算符不允许扩展和类似?
我有两位代码,据我所知,Ruby应该具有相同的function。 两者都在同一初始化方法中:
class TicTacToePlayer def initialize(player_type = { human: true }) # Here end end
第一个代码是标准的if / else语句:
if player_type[:human] extend Human else extend Joshua end
第二个是上面作为三元运算符:
player_type[:human] ? extend Human : extend Joshua
…
我希望两者function相同,但第一个运行顺利,第二个返回以下错误:
语法错误,意外的tCONSTANT,期待keyword_do或'{‘或’(’… yer_type [:human]?extend Human:extend Joshua#ternary op …
为什么不同?
使用括号进行函数调用
player_type[:human] ? extend(Human) : extend(Joshua)
作为使用像@ mtm的答案这样的括号的替代方法,您也可以这样写:
extend player_type[:human] ? Human : Joshua