三元运算符返回false。为什么?

时间:2015-07-09 14:23:27

标签: ruby

我有这段代码:

defmodule SlowRamp.Flood do
  def start_link do
    Task.start_link(fn -> start end)
  end

  defp start do
    receive do
      {:start, host, caller} ->
        send caller, System.cmd("cmd", ["opt"])
    end
  end
end

我将guessed_letter = [] word_to_guess = "hair" letter_holder = [] word_to_guess.split("").each do |letter| letter_holder << (guessed_letter.include?(letter)) ? letter : "_" end letter_holder.join('') 这个词拆分,"hair"数组中没有任何内容。三元运算符返回guessed_letter。它不应该为每个字母返回下划线吗?

2 个答案:

答案 0 :(得分:2)

重构您的代码:

guessed_letter = []
word_to_guess = "hair"
letter_holder = []
word_to_guess.split("").each do |letter|
  letter_holder << (guessed_letter.include?(letter) ? letter : "_")
end

letter_holder.join('')
# => "____"

原始代码有什么问题?

请看以下行:

letter_holder << (guessed_letter.include?(letter)) ? letter : "_"

按照优先顺序,此代码实际上意味着:

( letter_holder << (guessed_letter.include?(letter)) ) ? letter : "_"
|____________________________________________________| |____________|
                 |                                            |
                 .                                            .
    (Element getting inserted first)               (followed by ternary op on array)

因此,false总是guessed_letter.include?(letter)(因为false是一个空数组),所以始终获得guessed_letter

答案 1 :(得分:1)

这种行为是可以解释的。三元运算符的执行优先级非常低,因此Ruby认为您将布尔表达式添加到letter_holder数组中。

试试这个:

letter_holder << ((guessed_letter.include?(letter)) ? letter : "_")