Sorting Vertices by Z value

I have a list of vertices for a face (vertical face) and I want to find the vertex with the largest (highest) Z value. I’m thinking to start with a sort (sort_by) of the array first but maybe there is a easier way to do this?

Perhaps something like this?

v_list.sort_by! { |i| i.position[2] }
vtx_highest = v_list[0]

This should be faster:

vtx_highest = v_list.max_by { |i| i.position.z }
2 Likes

I never noticed that method! I goes back to at least Ruby 2.0 - probably longer?
I always used container.max { |a, b| a.position.z <=> b.position.z }

Using max_by it’s nicer syntax when you work with points as you can then do points.max_by(&:z). But in the case of vertices you need to use the block version.

1 Like

Don’t forget the ampersand …

points.max_by(&:z)
2 Likes

But the compressed (&:z) syntax is recent. Ruby 2+ I think.

1 Like

Ruby 2.0 was released in early 2013. It’s long since reached end of life. (Support for Ruby 2.3 has already ended). I’d argue it’s past “recent”.

Oh, how time flies.