← Back to Ruby Course | Chapter 12: Ruby Best Practices | Lesson 4 of 6

Truthiness (सिर्फ nil और false falsy हैं)

Ruby में, सिर्फ nil और false no count होते हैं, और बाकी सब yes count होता है, zero भी। यह एक door की तरह है जो दो special guests को छोड़कर सबके लिए खुलता है।
Syntax
ruby
if value
  # runs for anything except nil and false
end

Truthiness (सिर्फ nil और false falsy हैं)

Ruby में, एक boolean context में nil और false को छोड़कर हर value truthy है -- खासकर, कई दूसरी languages के उलट, 0 और "" (empty string) दोनों truthy हैं।

ऐसी languages से आने वाले developers के लिए यह एक frequent surprise है जहाँ 0 या empty collections falsy हैं। इस rule को exactly जानना subtle conditional bugs avoid करता है।

Warning: कई दूसरी languages के उलट, Ruby में 0 और "" (empty string) truthy हैं -- सिर्फ nil और false falsy हैं।

उदाहरण: Truthiness (only nil and false are falsy)

markup
puts "0 is truthy" if 0
puts "empty string is truthy" if ""
puts "this won't print" if nil
puts "this won't print either" if false
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. 0 को C या JavaScript की तरह false होने की उम्मीद करना, जब यह Ruby में truthy है।
  2. एक empty string या array के falsy होने की उम्मीद करना; .empty? इस्तेमाल करें।
  3. false और nil को separately check करने के लिए if x इस्तेमाल करना, जब दोनों falsy हैं और x.nil? सिर्फ nil test करता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.