Main Menu
  • Welcome to The RPG Maker Resource Kit.

Array function question

Started by da good king, July 11, 2009, 06:58:20 AM

0 Members and 1 Guest are viewing this topic.

da good king

 I was wondering about the sort method for Array. If you have an of some objects, such as an array of actors, can you sort or do other actions based on one or more of the object's values?

For example, you might have an array of actors which you need to sort by their agility for turn-taking. Likewise, I'm also wondering if you could use functions like union, intersection, or uniq based on one index value or multiple indeces' values.

An example would be that maybe I add some value to Game_Actor that's determined randomly, and I want the game to make an array of five of the same actor with a diff random_val and choose the one with the best random value of them. So, I'd want it to first sort them by random_val, and then use uniq, but because all though they're the same actor, they have a diff random_val, which normally would cause uniq to by-pass them, but in this case I want them deleted.

modern algebra

You can pass a block to sort. For instance:


actors.sort! { |a, b| a.agi <=> b.agi }


Would sort an array of actors by their agility.

As far as I know, you can't pass a block to uniq! However, seeing as you're sorting them first, I don't see why you can't just take the last element of the array.

da good king

 Well, that's because my example discluded the fact that what I'm doing would be more like having 10 groups of 2-5 (not even sure how many) similar actors all with different random_val's, so really I don't actually know exactly what index they end up at, and it's a little difficult to mark which arrays are similar. (the arrays are made up of [x, y, val], so the ones I need to be seen as similar are the matching coords)

Thx for the explanation on sort! tho, I didn't really get it the way they had it on the help contents.