Skip to content

Instantly share code, notes, and snippets.

@voxxit
Forked from mmcclimon/truthy.rb
Created February 4, 2016 19:05
Show Gist options
  • Save voxxit/2ac9a4f080fb7aee3446 to your computer and use it in GitHub Desktop.
Save voxxit/2ac9a4f080fb7aee3446 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
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