0

In C++ I can do this:

(condition ? sin : cos)(0.5);

or

typedef std::deque<int> T;
(T().*(condition ? &T::push_back : &T::push_front))(1);

What would be an equivalent of this in Ruby?

I know I can use send or method, but they allow me to call private methods.

# String#puts and String#print are private
("".method condition ? :puts : :print).call
detunized
  • 15,059
  • 3
  • 48
  • 64

1 Answers1

2

send is the way to go in Ruby. If you don't like it because it allows to call private methods, use public_send instead:

Math.public_send(condition ? :sin : :cos, 0.5)
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
tokland
  • 66,169
  • 13
  • 144
  • 170
  • Sounds kinda inefficient, though. I timed it and calling method directly is faster than calling it through `send`. In C++ there's no overhead, except for missed optimization opportunity. – detunized Nov 10 '12 at 14:32