本文介绍了为什么Ruby三元运算符不允许扩展和类似操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

据我了解Ruby,我有两段代码应具有相同的功能.两者都位于相同的initialize方法中:

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

第一个代码是标准的if/else语句:

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:

为什么有区别?

推荐答案

作为使用@mtm答案之类的括号的替代方法,您也可以这样写:

As an alternative to using parentheses like @mtm's answer, you can also write it like this:

extend player_type[:human] ? Human : Joshua

这篇关于为什么Ruby三元运算符不允许扩展和类似操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:54