在Ruby中用圆形切割数组

时间:2014-10-13 13:48:52

标签: ruby arrays slice

任何人都可以帮我改变这个"伪代码"对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

这是一个像这样的浮点数组:

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

1 个答案:

答案 0 :(得分:2)

您希望ceil向上舍入并each_slice来获取这些内容。

# 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 ) }

请注意,我将长度转换为带有to_f的浮点数,因为将一个整数除以另一个整数的结果始终为整数(向下舍入)。或者我可以做到:

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