A way-too-smart oneliner which uses recursion:
def collect_between(first, last)
first == last ? [first] : [first, *collect_between(first.next, last)]
end
An iterative solution:
def collect_between(first, last)
result = [first]
until first == last
first = first.next
result << first
end
result
end
EDIT: (Short) explanation of the asterix
It's called the splat operator. It "unrolls" an array:
array = [3, 2, 1]
[4, array] # => [4, [3, 2, 1]]
[4, *array] # => [4, 3, 2, 1]
some_method(array) # => some_method([3, 2, 1])
some_method(*array) # => some_method(3, 2, 1)
def other_method(*array); array; end
other_method(1, 2, 3) # => [1, 2, 3]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…