返回自身的 Ruby 方法 [英] Ruby method that returns itself

查看:24
本文介绍了返回自身的 Ruby 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些反思,但遇到了一个意想不到的障碍.

I am doing some reflection, and ran into an unexpected road block.

ruby(或rails)中是否有返回自身的对象方法

ruby-1.9.2> o = Object.new
 => #<Object:0x00000104750710> 
ruby-1.9.2> o.class
 => Object 
ruby-1.9.2> o.send :self
NoMethodError: undefined method `self' for #<Object:0x00000104750710>

我想要的

ruby-1.9.2> o.send :self
 => #<Object:0x00000104750710> 

这是内置的吗?或者我需要扩展对象(打开对象总是让我紧张):

Is this built in? Or do I need to extend Object (It always gets me nervous opening up Object):

class Object

  def itself
    self
  end

end

然后是:

ruby-1.9.2> o.send :itself
 => #<Object:0x00000104750710> 

<小时>

好的,关于我想要实现的目标的一些背景知识.我的 rails 应用程序中有一个通用的表助手,您可以这样调用:


Ok, some background on what I am trying to achieve. I have a generic table helper in my rails app, and you call if like so:

  render_list @person, [{field: :name, link_to: :itself},
                        {field: {address: :name}, link_to: :address}]

我一直在努力寻找调用 :itself 的正确方法——但我认为我的补丁是正确的方法.

I was struggling on the right way to call :itself -- but i'm thinking that my patch is the way to go.

推荐答案

是的!如果您有 Ruby 2.2.0 或更高版本,则可以使用 Kernel#itself 方法.

Yes! If you have Ruby 2.2.0 or later, you can use the Kernel#itself method.

您可以在此处查看对此功能的广泛讨论:https://bugs.ruby-lang.org/issues/6373.该补丁由 Rafael França 在消息 #53 中提交.

You can see the extensive discussion of this feature here: https://bugs.ruby-lang.org/issues/6373. The patch was submitted by Rafael França in message #53.

您可以在 object.c 中查看官方 Ruby 源代码.

You can see it in the official Ruby source by looking in object.c.

这篇关于返回自身的 Ruby 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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