代码之家  ›  专栏  ›  技术社区  ›  Mithun Sreedharan Kuldeep Modi

如何使用条件运算符(?:)红宝石?

  •  283
  • Mithun Sreedharan Kuldeep Modi  · 技术社区  · 15 年前

    条件运算符如何( ? : )用在红宝石里?

    例如,这是正确的吗?

    <% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
    
    6 回复  |  直到 7 年前
        1
  •  461
  •   the Tin Man    11 年前

    ternary operator

    if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this
    

    if if a then b else c end a ? b : c

    puts (if 1 then 2 else 3 end) # => 2
    
    puts 1 ? 2 : 3                # => 2
    
    x = if 1 then 2 else 3 end
    puts x                        # => 2
    

    puts if 1

    question = if question.size > 20 then
      question.slice(0, 20) + "..."
    else 
      question
    end
    
        2
  •  31
  •   DGM    15 年前
    puts true ? "true" : "false"
    => "true"
    
    
    puts false ? "true" : "false"
    => "false"
    
        3
  •  25
  •   the Tin Man    11 年前

    truncate

    <% question = truncate(question, :length=>30) %>
    
        4
  •  17
  •   the Tin Man    9 年前

    (true) ? 1 : 0
    

    \

    (true)   \
      ? 1    \
      : 0
    

    (true) ?
      1 :
      0
    

    ..


    true

    <% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
    

    <% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>
    

    <% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
                                       : question.question 
    %>
    

    <% question = if (question.size > 20)
                    question.question.slice(0, 20) + "..."
                  else 
                    question.question 
                  end
    %>
    

    question.question

        5
  •  3
  •   devwanderer    10 年前

    player_id=1
    ....
    player_id==1? enemy_id=2 : enemy_id=1
    # => enemy=2
    

    post

        6
  •  0
  •   Umesh Malhotra    7 年前

    condition ? statement_A : statement_B

    if condition == true
      statement_A
    else
      statement_B
    end