Skip to content

Instantly share code, notes, and snippets.

@xionon
Created January 20, 2014 15:50
Show Gist options
  • Save xionon/8522529 to your computer and use it in GitHub Desktop.
Save xionon/8522529 to your computer and use it in GitHub Desktop.
Show off default hash values
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