Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access `self` of an object through the parameters

Tags:

ruby

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.

like image 675
Lucas Steffen Avatar asked Dec 19 '22 21:12

Lucas Steffen


2 Answers

Not recommended, but instance_eval would somehow work:

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

And you can also break out of tap:

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

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)) }
like image 53
Stefan Avatar answered Jan 05 '23 20:01

Stefan


No, you can't do that. Receiver of a method (that array) is not accessible by some special name at the call site. Your best bet is assigning a name to that object.

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

Of course, if all you need is a random element, then .sample should be used. Which does not require evaluation of any arguments at the call site and its self is the array.

like image 40
Sergio Tulentsev Avatar answered Jan 05 '23 20:01

Sergio Tulentsev