By kyonides
Date 2010-08-03 00:23
Edited 2010-08-03 00:27
The other day I started using Ruby Structs and I also they could be very convenient, but I'm not sure if they'd be even worse than initializing too many separate instance variables. This is a sketch of what I did to create a single Struct that would include all the basic player stats in a single place inside a GamePlayer class.
class Stats < Struct.new(:name, :hp, :mp, :atk); end
class GamePlayer
def initialize
@basic_stats, @bonus_stats = Stats.new, Stats.new
end
end
Is it still better to initialize separate instance variables for every single value that's going to be stored in such a Struct? Or should I just forget about both of them and only use class methods in order to let the scripter or gamer retrieve the desired data?
For those not familiar with Structs I can tell you they are something like a combination of Arrays and Hashes and something more.
@basic_stats[:hp] = 125
...is the same thing as...
@basic_stats.hp = 125
@basic_stats
#=> <#struct :name = nil, :hp = 125, :mp = nil, :atk = nil>
why not just go:
Stats = Struct.new(:name, :hp, :mp, :atk)
Well, that was my first try but I noticed later that some things like Stats[:hp] = 125 didn't work for some weird reason and sometimes it automatically assigned a 0 value to the first variable. Since the first one might be a String for a name, I didn't like it and ended up creating a intermediate class.
Personally, I'm just using hashes for my game. Any particular reason why you decided to use Structs instead? To my knowledge, Structs are really only useful if you want a quick aggregate class that is only going to be used in a small, contained area.
I think it's easier to use the Struct class because I only create a single instance variable and every time I need to assign a new value to a hero attribute, it looks more self documenting than a single variable for every attribute, especially if I'm going to include some bonus stats feature there.
@basic_stats.hp = 125
@bonus_stats.mp += 25
Ah, ok. Well, I've kinda hidden the initialization of the Hash in another class which the class used for characters inherits from. Thus, in my opinion, it feels about the same as using a Struct.
Also, you could always do this.
stats = Hash.new
stats[:hp] = 10
or something, which might help clarify the code. I suppose it's really just a matter of choice though.
Loading...