Access `self` of an object through the parameters

前端 未结 4 776
太阳男子
太阳男子 2021-01-19 13:40

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

4条回答
  •  春和景丽
    2021-01-19 14:23

    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)) }
    

提交回复
热议问题