SORU
23 Kasım 2010, Salı


Nasıl koşullu operatör kullanırım (? :) Ruby?

Nasıl koşullu operatör (? :) Yakut kullanılır?

Örneğin, bu doğru mu?

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

CEVAP
23 Kasım 2010, Salı


ternary operator ve C gibi (parantez gerekli değildir) çalışır. Gibi çalışan bir ifade var:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

Ancak, Ruby, if de bir ifade yani.: if a then b else c end === a ? b : c, öncelikli meseleler hariç. Her iki ifade vardır.

Örnekler:

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

Unutmayın ilk vaka parantez gereklidir (aksi takdirde Yakut karıştı çünkü düşünüyor. puts if 1 ile bazı ekstra önemsiz sonra), ama onlar gerekli son durum " dedi sorun değil ortaya.

Kullanabilirsiniz "uzun" şeklinde okunabilirlik birden fazla satır için

question = if question.size > 20 then
  question.slice(0, 20)   "..."
else 
  question
end

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • nemoking of kinges

    nemoking of

    4 EYLÜL 2009
  • SunsetTrance

    SunsetTrance

    20 EYLÜL 2008
  • TheFlashCentre

    TheFlashCent

    22 Mayıs 2008