ruby 方法名称中的变量 [英] Variables in ruby method names

查看:59
本文介绍了ruby 方法名称中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

for attribute in site.device_attributes
  device.attribute
end

我希望代码将属性"的值替换为方法名称.

where I would like the code to substitute the value of "attribute" for the method name.

我尝试了 device."#{attribute}" 和各种排列.

I have tried device."#{attribute}" and various permutations.

这是完全不可能的吗?我错过了什么吗?

Is this completely impossible? Am I missing something?

我已经考虑过覆盖 method_missing,但是当我的问题是我需要调用一个未知"方法时,我无法弄清楚这对我有什么实际帮助.

I have considered overriding method_missing, but I can't figure out how that would actually help me when my problem is that I need to call an "unknown" method.

推荐答案

可以使用#send方法通过方法名调用对象的方法:

You can use #send method to call object's method by method's name:

object.send(:foo) # same as object.foo

您可以将参数传递给调用的方法:

You can pass arguments with to invoked method:

object.send(:foo, 1, "bar", 1.23) # same as object.foo(1, "bar", 1.23)

因此,如果变量attribute"中有属性名称,则可以使用

So, if you have attribute name in variable "attribute" you can read object's attribute with

object.send(attribute.to_sym)

并用

object.send("#{attribute}=".to_sym, value)

在 Ruby 1.8.6 中,#send 方法可以执行任何对象的方法,而不管其可见性(例如,您可以调用私有方法).这在 Ruby 的未来版本中可能会发生变化,您不应该依赖它.要执行私有方法,请使用 #instance_eval:

In Ruby 1.8.6 #send method can execute any object's method regardless of its visibility (you can e.g. call private methods). This is subject to change in future versions of Ruby and you shouldn't rely on it. To execute private methods, use #instance_eval:

object.instance_eval {
  # code as block, can reference variables in current scope
}

# or

object.instance_eval <<-CODE
  # code as string, can generate any code text
CODE

更新

您可以使用 public_send 调用与可见性规则相关的方法.

Update

You can use public_send to call methods with regard to visibility rules.

object.public_send :public_foo # ok
object.public_send :private_bar # exception

这篇关于ruby 方法名称中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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