user6776
user6776

Reputation: 37

Slice an array with round up in Ruby

Can anyone help me to transform this "pseudo code" to Ruby?

max = round_up(count(physical_values))
for i=0;i < max/100; i++
  part = physical_values[i*100..i*100+100]
  send_part_to_server(part)
end

It's a float array something like this:

11.05016861219201 10.350157930876776 10.550160982681064 11.550176241702957 12.55019150072485 12.750194552529138 11.850180819409616 10.350157930876776 9.15013962005014 9.15013962005014 10.450159456778692 12.15018539711582 13.250202182040084 12.95019760433388 11.750179293507244 10.65016250858298 10.850165560387723

Upvotes: 0

Views: 397

Answers (1)

Phrogz
Phrogz

Reputation: 303198

You want ceil to round up and each_slice to get the pieces.

# Slices of 100 elements each
physical_values.each_slice(100){ |part| send_part_to_server( part ) }

# <=100 slices
slice_size = (physical_values.length.to_f/100).ceil
physical_values.each_slice(slice_size){ |part| send_part_to_server( part ) }

Note that I converted the length into a float with to_f because the result of dividing one integer by another is always an integer (rounded down). Alternatively I could have done:

(physical_values.length/100.0).ceil # Use a floating point 100.0 for float result

Upvotes: 2

Related Questions