Access to the `self` object through parameters

Let's say I want to access an array element with a random index as follows:

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

Is there a way to pass the size of the array as follows?

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

Why should I do this? A great man once said: Science is not about why, but about why not.

+4
source share
4 answers

Not recommended, but instance_evalsomehow works:

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

And you can also breakfrom tap:

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

There is an open function request to add a method that gives selfand returns the result of a block. If this happens in Ruby, you can write:

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

, . ( ) . .

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

, , .sample. - , self - .

+4

instance_eval

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

, , Array#at , Array#sample .

[1,2,3,4].sample
#=> 3

If you don’t want to use instance_eval(or any form eval), then you can add the method to the class Arrayby patch of monkeys - generally speaking, I'm not sure if he is wise Idea for patch of monkey, though

class Array
  def random_index
    rand(size)
  end
end

["a","b","c","d"].random_index
#=> 2
+2
source

You can do something similar with lambda:

getrand = ->(x) { x[rand(x.count)] }
getrand.call [1,2,3]
# => 2 
+1
source

Source: https://habr.com/ru/post/1620594/


All Articles