nil คือ special Ruby object แทนค่า "empty" หรือ "default" เป็น falsy value (ทำงานเหมือน false ใน conditional) มีเพียง หนึ่ง nil object object_id = 4 (หรือ 8 ใน 64-bit)
nil.object_id # 4
Where Do Nil Values Come From?
หลายเมธอดคืน nil เมื่อหาค่าไม่เจอ: product not found, array index out of bounds, hash key ไม่มี
arr = [1,2,3] arr[5] # nil arr[5].size # NoMethodError: undefined method 'size' for nil:NilClass
Testing For Nil In Ruby
หลีกเลี่ยง error:
if array[5] && array[5].size # แบบเก่า if arr[5]&.size # Safe navigator &. (Ruby 2.3+) if @bacon.nil? # nil? method # blank? (Rails only)
เทคนิคหลีกเลี่ยง nil checking: fetch บน Hash/Array, Null Object Pattern
Other Places Where Nil Is Lurking
- Undefined instance variables:
@foo # nil(ระวัง typo หรือลืม initialize) puts/printคืนค่า nil เสมอ:[1,2,3].map { |n| puts n*2 } # [nil,nil,nil]แก้: ลบ puts ออกจาก block
Understanding NilClass
nil มีเมธอด to_something คืนค่าว่าง:
class NilClass
def to_s; ""; end
def inspect; "nil"; end
def nil?; true; end
def to_a; []; end
def to_f; 0.0; end
def to_i; 0; end
def to_c; Complex(0); end
def to_h; {}; end
end
เพราะ nil แทน "nothing"
Null Object Pattern
Sandi Metz: "Nothing is Something" nil หมายถึง nothing แต่สามารถมีความหมายเฉพาะได้
class MissingProduct def name; "Product not found"; end end
Array ผสม real products และ null products เรียก name ได้ทุกตัว ไม่ error → Polymorphism ใช้ได้ดีใน presentation layer แต่ controllers ต้องการแยก behavior
Truthiness
Ruby มี falsy เพียง 2 ค่า: nil และ false ทุกอย่างอื่น truthy (รวม 0):
if 0; puts 123; end # 123 (0 เป็น truthy!)
Summary
nil คือ Ruby object แทน nothing nil และ false เท่านั้นที่ falsy ทุกอย่างอื่น truthy