Harue
Harue

Reputation: 149

Extend send method of Object class

I want to change the send method in Ruby. My code is as follow

class A
  def send(symbol, *args)
     #customize code here
     #finally call the orinial __send__ function
     __send__(symbol, args)
  end
end

However, when I call the send function such as obj.send('a_var=', 10), I got this error:

ArgumentError: wrong number of arguments (1 for 0)

The error is at the line call __ send__ function. So how can I fix this error.

Upvotes: 0

Views: 67

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

For me your code is ok:

class A
  def send(symbol, *args)
     #customize code here
     #finally call the orinial __send__ function
     p 'this method has been called'
     __send__(symbol, args)
  end
  def show=(m)
   p m
  end

end

A.new.send('show=',1,3,4)
A.new.send('show=',1)
A.new.send(:show=,1)

Output:

"this method has been called"
[1, 3, 4]
"this method has been called"
[1]
"this method has been called"
[1]

Upvotes: 1

Zach Kemp
Zach Kemp

Reputation: 11904

If you want to pass the *args through to the __send__ call as individual arguments instead of an array, you need to deconstruct it there as well:

__send__(symbol, *args)

Upvotes: 1

Related Questions