I have a large array, h, that contains several instances of a parameter called startingParam, which is always followed by two other parameters that are related but not always the same. I need to look for every instance of startingParam in the array, and push it and the next two parameters into a separate array, holdingArray.
The following code is not working, due to the fact that I am very new to Ruby. Does anybody know what I am doing wrong? Is there a better way to approach the problem?
h.each do |param|
if param == 'startingParam'
holdingArray << h.[param],
holdingArray << h.[param + 1],
holdingArray << h.[param + 2]
end
end
Thanks so much.
You can grab the chunks using #slice_before:
arr = ['startingParam', 1, 2, 'startingParam', 3, 4]
arr.slice_before('startingParam')
# => [['startingParam', 1, 2], ['startingParam', 3, 4]]
If you created the original data structure, you may want to re-consider your design, however.
Functional approach:
>> ary = ['hello', 'startingParam', 1, 2, 'xyz', 'startingParam', 3, 4, 'bye']
>> ary.each_cons(3).select { |v, *vs| v == "startingParam" }.flatten(1)
=> ["startingParam", 1, 2, "startingParam", 3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With