Skip to content

Instantly share code, notes, and snippets.

@mmcclimon
Created December 17, 2013 15:56
Show Gist options
  • Save mmcclimon/8007176 to your computer and use it in GitHub Desktop.
Save mmcclimon/8007176 to your computer and use it in GitHub Desktop.
Port Perl's truthy values to Ruby.
#!/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
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