nahi / avl_tree

AVL tree and Red-black tree in Ruby
BSD 2-Clause "Simplified" License
66 stars 17 forks source link

Arguments not passed to a block provided with the ::new method #12

Open matt-wallis opened 6 years ago

matt-wallis commented 6 years ago

A block can be passed to Hash::new. The block will be run to produce default values. See Hash::new docs for how this works with Hashes. Note that the block expects 2 arguments.

For example

$ cat test_hash.rb
require 'pp'
t = Hash.new {|h, k| h[k] = []}
t[12] << "boo"
pp t.keys
pp t.values

$ ruby test_hash.rb
[12]
[["boo"]]

But with AVLTree:

$ cat test_avl_tree.rb
require 'avl_tree'
require 'pp'
t = AVLTree.new {|h, k| h[k] = []}
p "OK so far"
t[12] << "boo"
pp t.keys
pp t.values

$ ruby test_avl_tree.rb
"OK so far"
test_avl_tree.rb:3:in `block in <main>': undefined method `[]=' for nil:NilClass (NoMethodError)
    from /Users/matt/.gem/ruby/2.4.0/gems/avl_tree-1.2.1/lib/avl_tree.rb:409:in `default_value'
    from /Users/matt/.gem/ruby/2.4.0/gems/avl_tree-1.2.1/lib/avl_tree.rb:378:in `[]'
    from test_avl_tree.rb:5:in `<main>'
matt-wallis commented 6 years ago

Pull request submitted: https://github.com/nahi/avl_tree/pull/13