Marshal cannot reset proc hash by default (TypeError)

I have this ruby ​​script that generates a hash and saves it to a file.

Sometimes a file does not exist or is empty, so I always check for its presence. Then I load the old values ​​into my hash and try to save again. I struggled with this for a long time. This is an example:

newAppName = ARGV[0] newApp = Hash.new newApp["url"] = ARGV[1] newApp["ports"] = ARGV[2].to_i apps = Hash.new { |h, k| h[k] = Hash.new } # apps["test"] = {"url" => "www.test.com", "ports" => 3 } appsFile = '/home/test/data/apps' if File.exists?(appsFile) apps = Marshal.load File.read(appsFile) else puts "Inserting first app into list..." end apps[newAppName] = newApp serialisedApps = Marshal.dump(apps) # This line is where I get the error File.open(appsFile, 'w') {|f| f.write(serialisedApps) } 

Now I get this error:

 script.rb:53:in `dump': can't dump hash with default proc (TypeError)` 

What does it mean? Is my hash wrong? How to fix it?

I tried to do it manually with irb and it worked fine, although I tested on Mac and this script works on Linux. They should not behave differently, right?

+4
source share
1 answer

Ruby does not have a Marshal format for code, only for data. You cannot marshal Proc or lambdas.

Your apps hash has default_proc because

 hsh = Hash.new { some_block } 

more or less coincides with

 hsh = {} hsh.default_proc = ->{ some_block } 

IOW: your apps hash contains code, and the code cannot be sorted.

+17
source

Source: https://habr.com/ru/post/1445754/


All Articles