Search code examples
rubychaining

How to method chain shift and sample in one line


Say you have an array:

a = [2, 5, 8]

To get rid of the first element, so you can use shift:

a.shift # => 2
a # => [5, 8]

There is no problem doing sample on a:

a.sample # => 5

It doesn't seem possible to do both methods chained. You get

a.shift.sample # => undefined method `sample' for 2:Fixnum

What would be the most efficient and concise way to do this? The context is iterating through winning_combo arrays for a Ruby tic tac toe program. I do not want to modify the original array.


Solution

  • use the below :

    a = [2, 5, 8]
    p a.drop(1).sample #=>5
    a = [2, 5, 8]
    p a.drop(1).sample #=>8