Why does the Ruby ternary operator not allow extending and similar? [duplicate]

安稳与你 提交于 2019-12-25 02:43:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!