Ruby : ทุกอย่างมันเป็น Object


>> 1.class
=> Fixnum
>> 1.0.class
=> Float
>> ''.class
=> String
>> true.class
=> TrueClass
>> false.class
=> FalseClass
>> 1.class.class
=> Class
>> nil.class
=> NilClass

กรณีประหลาดของมันก็คือ true กับ false มันเสือกเป็นคนละ class กัน
จดไว้เลยละกันกันลืมว่าไอ้ boolean เนี่ยมันเป็นยังไงกัน

if nil
    puts 'nil is true'
else
    puts 'nil is false'
end

if nil == true
    puts 'nil == true'
elsif nil == false
    puts 'nil == false'
else
    puts 'nil != true and nil != false'
end

if 0
    puts '0 is true'
else
    puts '0 is false'
end

if 0 == true
    puts '0 == true'
elsif 0 == false
    puts '0 == false'
else
    puts '0 != true and 0 != false'
end
items = [1,1.0,'abc',  nil, [],true , false]
puts "#{items.inspect}"
items.each do |test|
  if !!test == test
    puts "#{test.class} IS boolean"
  else
    puts "#{test.class} is NOT boolean"
  end
end

ผลจ้า

nil is false
nil != true and nil != false
0 is true
0 != true and 0 != false
[1, 1.0, "abc", nil, [], true, false]
Fixnum is NOT boolean
Float is NOT boolean
String is NOT boolean
NilClass is NOT boolean
Array is NOT boolean
TrueClass IS boolean
FalseClass IS boolean
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s