与Ruby的public_send方法等效吗? [英] Any equivalent of Ruby's public_send method?

查看:138
本文介绍了与Ruby的public_send方法等效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,要构造方法的名称并将其发送给对象,可以执行以下操作:

class Foo
  def foo
    "FOO"
  end
end

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

什么是等效的Crystal技术?

解决方案

您应该记住,与Ruby不同,Crystal是一种编译后的静态类型语言,因此Ruby的动态功能无法很好地映射到它. /p>

Crystal替代动态的方法是支持-但它们并非如此相同,并且您不应该期望它们以相同的方式工作.

具体来说,您不能使用宏在运行时选择 要调用的方法-在Crystal中您根本无法做到这一点.

但是您的问题可能是 XY问题-询问您的问题实际上正在尝试解决,并且可能对此有解决方案.

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?

解决方案

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.

这篇关于与Ruby的public_send方法等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆