Any equivalent of Ruby's public_send method?

2019-08-21 17:47发布

问题:

In Ruby, to construct a method's name and send it to an object, one can do:

class Foo
  def foo
    "FOO"
  end
end

Foo.new.public_send(:foo)  # => "FOO"
Foo.new.public_send("foo") # => "FOO"

What is equivalent technique for Crystal?

回答1:

You should remember that Crystal, unlike Ruby, is a compiled, statically-typed language, so dynamic features of Ruby don't map that well to it.

Crystal's alternative to dynamism is support for macros - but they are not the same, and you shouldn't expect them to work in the same way.

Specifically, you can't use macros to pick at runtime the method to be called - in Crystal you can't do that, at all.

But your question is probably an XY problem - ask for what you're actually trying to solve, and there may be a solution for that.



回答2:

There is no equivalent in crystal. Crystal is a statically typed and statically compiled language. We have no send or eval functions.

Depending on the problem you had which made you reach for send in the first place, you might be able to use macros. There is not one replacement for send in crystal, there is simply a bunch of tools to enable some dynamic behaviour to be modelled statically.