One line if statement not working

前端 未结 8 908
遥遥无期
遥遥无期 2021-01-29 18:59
<%if @item.rigged %>Yes<%else%>No<%end%>

I was thinking of something like this?

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


        
相关标签:
8条回答
  • 2021-01-29 19:28

    For simplicity, If you need to default to some value if nil you can use:

    @something.nil? = "No" || "Yes"
    
    0 讨论(0)
  • 2021-01-29 19:31

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

    Ternary operator has form condition ? if_true : if_false

    0 讨论(0)
  • 2021-01-29 19:35

    Both the shell and C one-line constructs work (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"
    
    0 讨论(0)
  • 2021-01-29 19:41

    One line if:

    <statement> if <condition>
    

    Your case:

    "Yes" if @item.rigged
    
    "No" if !@item.rigged # or: "No" unless @item.rigged
    
    0 讨论(0)
  • 2021-01-29 19:42

    You can Use ----

    (@item.rigged) ? "Yes" : "No"

    If @item.rigged is true, it will return 'Yes' else it will return 'No'

    0 讨论(0)
  • 2021-01-29 19:44

    In Ruby, the condition and the then part of an if expression must be separated by either an expression separator (i.e. ; or a newline) or the then keyword.

    So, all of these would work:

    if @item.rigged then 'Yes' else 'No' end
    
    if @item.rigged; 'Yes' else 'No' end
    
    if @item.rigged
      'Yes' else 'No' end
    

    There is also a conditional operator in Ruby, but that is completely unnecessary. The conditional operator is needed in C, because it is an operator: in C, if is a statement and thus cannot return a value, so if you want to return a value, you need to use something which can return a value. And the only things in C that can return a value are functions and operators, and since it is impossible to make if a function in C, you need an operator.

    In Ruby, however, if is an expression. In fact, everything is an expression in Ruby, so it already can return a value. There is no need for the conditional operator to even exist, let alone use it.

    BTW: it is customary to name methods which are used to ask a question with a question mark at the end, like this:

    @item.rigged?
    

    This shows another problem with using the conditional operator in Ruby:

    @item.rigged? ? 'Yes' : 'No'
    

    It's simply hard to read with the multiple question marks that close to each other.

    0 讨论(0)
提交回复
热议问题