简体   繁体   中英

Iterate over array and first again

In order to export the coordinates of a polygon with n points I need to have n+1 points. The additional one is supposed to "close" the polygon. Currently I simply iterate over the whole array and do it manually again for the first:

face.outer_loop.vertices.each do |g|
    xml.Grafic(
        :X=>g.position.x, 
        :Y=>g.position.y, 
        :Z=>g.position.z)
end
xml.Grafic(
    :X=>face.outer_loop.vertices[0].x, 
    :Y=>face.outer_loop.vertices[0].y, 
    :Z=>face.outer_loop.vertices[0].z)

Is there a more elegant solution?

I can think about:

COORDS = %i(X Y Z)
(face.outer_loop.vertices + [face.outer_loop.vertices.first]).each do |g|
  values = COORDS.map do |c|
    g.position.public_send "#{c.to_s.downcase}"
  end
  xml.Graphic COORDS.zip(values).to_h
end

or use each_with_object to not pollute coords in the global namespace:

(face.outer_loop.vertices + [face.outer_loop.vertices.first]).each_with_object(%i(X Y Z)) do |g, coords|
  values = coords.map do |c|
    g.position.public_send "#{c.to_s.downcase}"
  end
  xml.Graphic coords.zip(values).to_h
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM