简体   繁体   中英

Calling objects like methods in ruby

Is it (in any way, no matter how weird or ugly) possible to call an object like a method. I'm not talking about method objects or calling an object's method, I mean this:

class Klass
  def callMeMethod *args
    p args
  end
end

myObject = Klass.new

myObject *args  #=> [arg0, arg1, ...]
myObject(*args) #=> [arg0, arg1, ...]

I thought about defining a new global method each time an object is created (never mind how terrible that is) but I ran into problems, also I would ideally like to call it even if it's returned from some expression such as:

someArray[index_of_my_object] *args  #=> [arg0, arg1, ...]
someArray[index_of_my_object](*args) #=> [arg0, arg1, ...]

So basically Python's __call__ method.

thanks

No.

This has been asked many, many times over many, many years.

Yehuda Katz wrote a blog post about it, titled Ruby is NOT a Callable Oriented Language (It's Object Oriented) , and the title says pretty much what the Ruby community thinks about this. Ruby is centered around objects, not functions. Message sending is the fundamental operation, not function calls.

There is an ambiguity between a message send with no explicit receiver and a function call. Scala solves this ambiguity with static typing, but Ruby can't do that, so the ambiguity is simply resolved by not having function calls, or rather by using a different syntax for function calls ( foo.(bar) instead of foo(bar) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM