1

when i write method missing in Object class i'm getting the output different in each interface.

the code is

class Object
  def method_missing(hgh)
    puts self
  end
end

when i use REPL like irb, i get

enter image description here

when i use the command line, i get no error, any reasons would be helpful, thanks in advance

1 Answers1

3

The tl;dr answer is that both are correct. Just more stuff happen in the REPL.


When you run the code from the command line like:

ruby script.rb

All that happens is that it's evaluated.

Whereas REPLs like IRB read your input, evaluate it and print it in a loop.

In this case evaluating your code literally broke the REPL and resulted in the subsequent print failing.


Now you may be a bit confused by this. "There is a print in both cases, I use puts!". The print I'm referring to here is the result that gets visualised after each evaluation. In this case the method definition result (=> :method_missing).


It might not only be the printing itself. It can be the ton of other under the hood code that the REPL has to execute to keep state like "what code was defined on which line" and so on.

Think of what you just did - you made it so that every object has every method possible to return nil. That is not just for the code you write in the REPL. It's for the code of the REPL itself as well.

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
  • 1
    This. The REPL is a complex piece of Ruby code, and the OP just modified fundamentally how every single object in the system behaves. It would be very surprising if this *didn't* break something. – Jörg W Mittag Nov 07 '19 at 15:31
  • @ndnenkov In this scenario, what is the problem with writing "method_missing" method over there. If that was any other new method, it would not throw any error. Can i know why is this code behaving ODD! – Ramireddy Samar Nov 08 '19 at 06:45
  • @RamireddySamar `method_missing` is a special method in Ruby that gets invoked if you try to invoke a method on an object that doesn't exist. Ex. `4.foo` will invoke `4.method_missing :foo` as `4` doesn't have a `foo` method. So in a sense you just made it so `4` has `foo` (and any other method for that matter). That's what is so special about `method_missing` as opposed to other method names. – ndnenkov Nov 08 '19 at 07:23
  • @ndnenkov It seems like, only when i have any code inside method_missing i.e. `puts self` , i get this error, if it contains nothing like `method_missing(met) do end` then i'm not getting any error, what about this? – Ramireddy Samar Nov 11 '19 at 13:04
  • @RamireddySamar can you try this: `def method_missing(hgh); puts self; super; end` instead of your current implementation? (Aka just add a `super` at the end). – ndnenkov Nov 11 '19 at 13:09
  • yes, but if that logic is calling super, then it should print the output(self) in console for every method call right? if yes, y am i not getting any output?. if no, why? – Ramireddy Samar Nov 13 '19 at 05:33