-
-
Save voxxit/2ac9a4f080fb7aee3446 to your computer and use it in GitHub Desktop.
Port Perl's truthy values to Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Object | |
# The following are falsy: false, nil, 0, "", and empty arrays/hashes. | |
# Anything else falls is truthy. This emulates Perl's truthiness. | |
def truthy? | |
if self.nil? | |
return false | |
elsif self.is_a? Fixnum | |
return self != 0 | |
elsif self.is_a? String | |
return !self.empty? | |
elsif self.is_a? Array | |
return self.length > 0 | |
elsif self.is_a? Hash | |
return self.length > 0 | |
else | |
return !!self | |
end | |
end | |
def falsy? | |
!truthy? | |
end | |
end | |
# Double-check truthy values | |
checks = [nil, 0, 1, '', 'test', 0.0, [], [nil], {}, {:a => 1}, false, true] | |
checks.each do |v| | |
puts "#{v.inspect}.truthy?\t= #{v.truthy?}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment