通过参数访问对象的`self` [英] Access `self` of an object through the parameters

查看:39
本文介绍了通过参数访问对象的`self`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想以这种方式访问​​随机索引处的数组元素:

Let's say I want to access an element of an array at a random index this way:

[1, 2, 3, 4].at(rand(4))

有没有办法像下面这样传递数组的大小?

Is there a way to pass the size of the array like the following?

[1, 2, 3, 4].at(rand(le_object.self.size))

我为什么要这样做?--一位伟人曾经说过:科学不在于为什么,而在于为什么不.

Why would I do that?--A great man once said: Science isn't about why, it is about why not.

推荐答案

不推荐,但 instance_eval 会以某种方式工作:

Not recommended, but instance_eval would somehow work:

[1, 2, 3, 4].instance_eval { at(rand(size)) }

你也可以break <代码>点击:

[1, 2, 3, 4].tap { |a| break a.at(rand(a.size)) }

有一个开放的功能请求来添加一个产生self<的方法/code> 并返回块的结果.如果这使它成为 Ruby,你可以这样写:

There's an open feature request to add a method that yields self and returns the block's result. If that makes it into Ruby, you could write:

[1, 2, 3, 4].insert_method_name_here { |a| a.at(rand(a.size)) }

这篇关于通过参数访问对象的`self`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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