Skip to content

Instantly share code, notes, and snippets.

@rsutphin
Created November 25, 2009 21:35
Show Gist options
  • Save rsutphin/243048 to your computer and use it in GitHub Desktop.
Save rsutphin/243048 to your computer and use it in GitHub Desktop.
def visit(h, incr)
puts "Visiting #{h.inspect}"
visited_keys = []
begin
h.each_pair do |k, v|
visited_keys << k
h[incr.call(k)] = v
if h.size > 20 # arbitrary limit
raise "Infinite loop!"
end
end
puts "Visited keys: #{visited_keys.inspect}"
rescue => e
puts e
puts "Keys so far: #{visited_keys.inspect}"
end
end
visit({ 1 => 101, 2 => 102, 3 => 103, 4 => 104 }, lambda { |k| k + 1000 })
visit({ :a => :a, :b => :b, :c => :c }, lambda { |k| "#{k}_" })
$ jruby --version
jruby 1.4.0 (ruby 1.8.7 patchlevel 174) (2009-11-25 6586) (Java HotSpot(TM) Client VM 1.5.0_20) [i386-java]
$ jruby hash_modification.rb
Visiting {1=>101, 2=>102, 3=>103, 4=>104}
Infinite loop!
Keys so far: [1, 2, 3, 4, 1001, 1002, 1003, 1004, 2001, 2002, 2003, 2004, 3001, 3002, 3003, 3004, 4001]
Visiting {:a=>:a, :b=>:b, :c=>:c}
Infinite loop!
Keys so far: [:a, :b, :c, "a_", "b_", "c_", "a__", "b__", "c__", "a___", "b___", "c___", "a____", "b____", "c____", "a_____", "b_____", "c_____"]
$ ruby --version
ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-linux]
$ ruby hash_modification.rb
Visiting {1=>101, 2=>102, 3=>103, 4=>104}
Visited keys: [1, 2, 3, 4]
Visiting {:a=>:a, :b=>:b, :c=>:c}
Visited keys: [:a, :b, :c, "c_", "b_", "a_"]
$ ruby1.9 --version
ruby 1.9.0 (2008-06-20 revision 17482) [i486-linux]
$ ruby1.9 hash_modification.rb
Visiting {1=>101, 2=>102, 3=>103, 4=>104}
Infinite loop!
Keys so far: [1, 2, 3, 4, 1001, 1002, 1003, 1004, 2001, 2002, 2003, 2004, 3001, 3002, 3003, 3004, 4001]
Visiting {:a=>:a, :b=>:b, :c=>:c}
Infinite loop!
Keys so far: [:a, :b, :c, "a_", "b_", "c_", "a__", "b__", "c__", "a___", "b___", "c___", "a____", "b____", "c____", "a_____", "b_____", "c_____"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment