布尔练习

Boolean exercise

我正在做课程中的以下练习,但我无法全神贯注。本人初学Rails,请耐心等待。目前这个练习要我写一个名为 tasty? 的方法,它有一个参数:

def tasty?(ripe)  
end  

tasty? 应该:

规格为:

describe "tasty?" do  
  it "should return 'Yes' if ripe is true" do  
    expect( tasty?(true) ).to eq("Yes")  
  end  
  it "should return 'Not Yet' if ripe is false" do  
    expect( tasty?(false) ).to eq("Not Yet")  
  end  
end  

我写了这个:

def tasty?(ripe)  
  if "ripe == 'yes'"  
    ( tasty?("true") ).==("yes")  
  end  
  if "ripe == 'not yet'"  
    ( tasty?("false") ).==("not yet")  
  end  
end  

当我 运行 收到此消息时:

exercise.rb:4: warning: string literal in condition  
exercise.rb:7: warning: string literal in condition  

谁能告诉我我做错了什么?谢谢您的帮助。

您收到的错误是由于 if 语句中的字符串;您应该删除引号,例如:

if ripe == 'yes'

但是,由于 ripe 显然始终是布尔值 truefalse 而不是字符串 "yes",因此您不应将其与 "yes".您应该能够将其直接传递给 if 语句:

if ripe
  …
else
  …
end

然后您可以简单地 return 不同条件所需的字符串:

if ripe
  "Yes"
else
  "Not yet"
end

这有意义吗?

根据规范,我会这样写:

def tasty?(ripe)
  ripe ? 'Yes' : 'Not Yet'
end

这也可以更详细地写成:

def tasty?(ripe) 
  if ripe
    'Yes'
  else 
    'Not Yet' 
  end 
end

您方法的参数 ripe 将根据您提供的规范为真或假。因此,在您的方法中,您需要检查 ripe 是真还是假,然后 return 是正确的字符串(即是或尚未)。

我的第一个示例使用 ternary operator,它是 if/else 语句的 shorthand 表达式(如我的第二个代码块所示)。

基本上,它只是询问 ripe 是否为真,如果是,它 returns 'Yes'。如果不是,它 returns 'Not Yet'。

由于@eirikir 向您展示了错误或您的方式,我将解决另一个问题。

试试这个:

def tasty?(ripe)
  if ripe==true
    puts "Yes"
  else
    puts "Not Yet"
  end
end

然后

tasty?(true)  #=> "Yes"
tasty?(false) #=> "Not Yet"
tasty?(nil)   #=> "Not Yet"
tasty?(42)    #=> "Not Yet"

最后一个returns"Not Yet"因为:

 42==true #=> false

现在试试这个:

def tasty?(ripe)
  if ripe
    puts "Yes"
  else
    puts "Not Yet"
  end
end

然后:

tasty?(true)  #=> "Yes"
tasty?(false) #=> "Not Yet"
tasty?(nil)   #=> "Not Yet"
tasty?(42)    #=> "Yes"

tasty?(42) 现在 returns "Yes" 因为 ripe 计算 true。这是因为,在逻辑表达式(例如 if..)中,如果对象等于 falsenil。如果等于 falsenil.

,则称其为 "falsy"

@craig 展示了如何简化后面的表达式。