Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Sorting an array of items by id.

Let's say you have an array of items/weapons/armor. How would you sort the array by the item's id?

Also how would you make the items appear first, then the weapons, then the armor?
 
I would do this by to making a compare method <=> in RPG::Item RPG::Weapon and RPG::Armor It would look something like this

array.sort! {|a,b| b - a}

Compare method add this in RPG::(Item, Weapon, Armor) (First Draft try it to see if it works May still have something wrong in it)

Code:
def <=> (other)
classes = ["RPG::Armor", "RPG::Weapon", "RPG::Item"]
if classes.index(self.class.to_s) > classes.index(other.class.to_s)
  return 1
elsif classes.index(self.class.to_s) < classes.index(other.class.to_s)
  return -1
else
  return self.id <=> other.id
end
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top