From: Stefano Crocco Date: 2013-02-18T04:49:00+09:00 Subject: Re: What is Ruby's default constructor? On Monday 18 February 2013 Love U Ruby wrote > >> class A > >> > >> def Object.new initialize > >> > >> p "hi" > >> rescue > >> > >> end > >> end > > => nil > > >> begin # <~~~ Here I have pressed on ENTER > > "hi" > /usr/lib/ruby/1.9.1/irb/ruby-token.rb:94:in `Token': undefined > method `set_backtrace' for "hi":String (NoMethodError) > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:348:in `block in > lex_init' > from /usr/lib/ruby/1.9.1/irb/slex.rb:236:in `call' > from /usr/lib/ruby/1.9.1/irb/slex.rb:236:in `match_io' > from /usr/lib/ruby/1.9.1/irb/slex.rb:221:in `match_io' > from /usr/lib/ruby/1.9.1/irb/slex.rb:75:in `match' > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:286:in `token' > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:262:in `lex' > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:233:in `block (2 levels) > in each_top_level_statement' > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `loop' > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `block in > each_top_level_statement' > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `catch' > from /usr/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in > `each_top_level_statement' > from /usr/lib/ruby/1.9.1/irb.rb:155:in `eval_input' > from /usr/lib/ruby/1.9.1/irb.rb:70:in `block in start' > from /usr/lib/ruby/1.9.1/irb.rb:69:in `catch' > from /usr/lib/ruby/1.9.1/irb.rb:69:in `start' > from /usr/bin/irb:12:in `
' > @ubuntu:~$ > > > > Now my question is :- > > - how the "hi" has been printed? > > - what is the reason of the error as above printed > > - if such an `initialize` definition is not allowed then why error has > not come after I ended with the `class` definition? > I'm not sure what you're trying to accomplish here. However, this is what's happening: > >> class A > >> > >> def Object.new initialize You're overriding Object.new. This will affect any object's creation. Since you're not even calling super (that is, the original Object.new) the new object will not even be created. All this method will do is print a string > >> rescue > >> end > >> end No idea of what exactly this does here. > >> begin I guess that, since you're seriously messing with ruby core functionality (after all, you've completely changed how objects are created), something in IRB brokes, causing the error you seee. If you try running that code from a script, you'll simply get a syntax error because of a missing end. What are you training to achieve, exactly? Stefano