0

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

10
  • thinks link it's of your interest stackoverflow.com/questions/35400337/ruby-send-vs-call-method Commented Apr 15, 2017 at 17:35
  • no, I'm talking about calling the object as if it were a method (object variable # => result) Commented Apr 15, 2017 at 17:47
  • Implement #call and #[] methods just like Proc and Method. I think that would be more a natural interface in Ruby. Commented Apr 15, 2017 at 17:47
  • Yeah, yeah, more natural is good and I know I can define methods, I'm talking about a very specific thing that, as far as I understand, is completely against the concept of ruby methods and yet I'm sure there's a way to hack it together Commented Apr 15, 2017 at 17:49
  • I think you're taking the wrong approach here. Write Ruby when you're working with Ruby, don't try to make it behave like some other language. Why do you need to do it this way? Commented Apr 15, 2017 at 17:53

1 Answer 1

2

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)).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.