2025-03-09 08:00:04

一行if语句不工作

<%if @item.rigged %>Yes<%else%>No<%end%>

我在想这样的东西?

if @item.rigged ? "Yes" : "No" 

但这并不奏效。Ruby有||=,但我甚至不知道如何使用那个东西。


当前回答

if apple_stock > 1
  :eat_apple
else
  :buy_apple
end

上面的语句可以在ruby中写成三元语句的形式:

apple_stock > 1 ? :eat_apple : :buy_apple

其他回答

一行,如果:

<statement> if <condition>

你的情况:

"Yes" if @item.rigged

"No" if !@item.rigged # or: "No" unless @item.rigged

你可以使用:

(@item.rigged) ?“是”:“不是”

如果@item。如果操纵为真,它将返回'Yes'否则它将返回'No'。

别忘了它可以从ruby标签中生成内容:

  v
<%= @item.rigged? ? "Yes" : "No" %>

标记(v)表示使用等号在html中生成文本。

shell和C的单行结构都可以工作(ruby 1.9.3p429):

# Shell format
irb(main):022:0> true && "Yes" || "No"
=> "Yes"
irb(main):023:0> false && "Yes" || "No"
=> "No"

# C format
irb(main):024:0> true ? "Yes" : "No"
=> "Yes"
irb(main):025:0> false ? "Yes" : "No"
=> "No"
if apple_stock > 1
  :eat_apple
else
  :buy_apple
end

上面的语句可以在ruby中写成三元语句的形式:

apple_stock > 1 ? :eat_apple : :buy_apple