Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically calling a method whenever an instance is called

Tags:

ruby

I have several classes, e.g., P, that share the same instance method some_method:

class P
  ...
  def some_method
    @id
  end
end

Instances of these classes will be used as arguments at many places like this:

p = P.new
q = Q.new
...

def some_outside_method(p,q,r,s)
  another_outside_method(p.some_method, q.some_method, r.some_method, s.some_method)
end

I'm wondering if there is a more elegant way of writing it. Is it possible to automatically call p's some_method whenever p is referenced as in some_outside_method(p)? It is something like to_s implicitly called by puts, but more generalized.

like image 209
zuhao Avatar asked Aug 31 '26 16:08

zuhao


1 Answers

You can reduce duplication by doing this, for example:

def some_outside_method(p,q,r,s)
  args = [p, q, r, s].map{|o| o.send(:some_method)}
  another_outside_method(*args)
end

or, more briefly:

def some_outside_method(*args)
  args = args.map(&:some_method)
  another_outside_method(*args)
end

or, more more briefly:

def some_outside_method(*args)
  another_outside_method args.map(&:some_method)
end

But don't. Simple code is better than terse and "clever" one.

like image 132
Sergio Tulentsev Avatar answered Sep 03 '26 09:09

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!