Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value of three consecutive elements in array

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.

like image 365
Isaac Lewis Avatar asked Dec 30 '25 14:12

Isaac Lewis


2 Answers

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.

like image 61
d11wtq Avatar answered Jan 02 '26 02:01

d11wtq


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]
like image 34
tokland Avatar answered Jan 02 '26 04:01

tokland