Monkey Patch Object gives strange results

I hacked the to_hash object for Object (I'm not saying this is a good idea, just an experiment). When I ran into an odd issue where IO stopped working.

 #lib/object.rb class Object def to_hash self.instance_variables.inject({}) { |hash,var| hash[var.to_s.delete("@")] = self.instance_variable_get(var); hash } end end #run_test1.rb require_relative 'lib/Object' require 'FileUtils' puts 'run test' #run_test2.rb require_relative 'lib/Object' File.open('test.txt', 'w') {|f| f.write('this is a test')} 

in run_test1 I get

 <internal:lib/rubygems/custom_require>:29:in `set_encoding': wrong number of arguments (0 for 1..2) (ArgumentError) from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from .../run_test1.rb:2:in `<main>' 

in run_test2 I get

 run_test2.rb:3:in `initialize': No such file or directory - test.txt (Errno::ENOENT from run_test2.rb:3:in `open' from run_test2.rb:3:in `<main>' 

(if the file exists, it says the file is not open for writing)

Until I'm surprised this happened - just curious what is going on here? Theoretically, this should be good, but what is the main reason.

Relevant Information:

  • ruby 1.9.2p290 (2011-07-09) [i386-mingw32]
  • XP SP3 32-bit
  • VERSION OF ABROADS: 1.8.12
+4
source share
1 answer

The to_hash method to_hash used to identify objects that force Hash. In this sense, it behaves like to_ary or to_str . This method is more like to_a or to_s .

A lot of Ruby code, including the main Ruby code, checks for the presence of to_hash to determine if the argument hash parameters ( arg.respond_to? :to_hash ) and from there follow a different execution path. This becomes even more confusing code verification if the object is a real hash or not ( Hash === arg ).

You might want to name your to_h method or something similar.

+2
source

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


All Articles