Created
January 20, 2014 15:50
-
-
Save xionon/8522529 to your computer and use it in GitHub Desktop.
Show off default hash values
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
puts "hash_without_default = Hash.new" | |
hash_without_default = Hash.new | |
print "hash_without_default[:key] # => " | |
puts hash_without_default[:key].inspect | |
print "hash_without_default[:key][:value] # => " | |
begin | |
puts hash_without_default[:key][:value].inspect | |
rescue => e | |
puts "error: #{e}" | |
end | |
puts | |
puts "-------------------------------" | |
puts | |
puts "hash_with_default = Hash.new {|h, k| h[k] = {}}" | |
hash_with_default = Hash.new {|h, k| h[k] = {}} | |
print "hash_with_default[:key] # => " | |
puts hash_with_default[:key].inspect | |
print "hash_with_default[:key][:value] # => " | |
begin | |
puts hash_with_default[:key][:value].inspect | |
rescue => e | |
puts "error: #{e}" | |
end | |
# $ ruby hashtest.rb | |
# hash_without_default = Hash.new | |
# hash_without_default[:key] # => nil | |
# hash_without_default[:key][:value] # => error: undefined method `[]' for nil:NilClass | |
# | |
# ------------------------------- | |
# | |
# hash_with_default = Hash.new {|h, k| h[k] = {}} | |
# hash_with_default[:key] # => {} | |
# hash_with_default[:key][:value] # => nil | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment