oop - Ruby - Setter methods for hash properties -
i've been tooling around ruby converting pen , paper rpg script.
right have character's stats kept in hash, able set via public method. got working with:
class character attr_reader :str, :con, :dex, :wis, :int, :level, :mods, :stats def initialize str, con, dex, wis, int, cha, level = 1 @stats = { :str => str, :con => con, :dex => dex, :wis => wis, :int => int, :cha => cha } @mods = {} @level = level @stats.each_pair |key, value| @mods[key] = ((value / 2 ) -5).floor end end def []=(index, value) @stats[index] = value end end this allows me instantiate new character, update @stats running newchar.stats[:str] = 12
however, seem able modify @mods using method well, undesirable. newchar.mods[:str] = 15 alter @mods hash, understanding should not possible current setter method.
on separate note, iterator i'm using create @mods hash seems clunky haven't found better accomplish task.
you did not call []= method in example. done so:
newchar[:str] = 123 instead of
newchar.stats[:str] = 123 so call newchar.stats[:str] = 123 not need method definition. reason newchar.stats newchar.mods both return actual hash can altered.
one possible workaround freeze @mods variable can't altered more:
def initialize str, con, dex, wis, int, cha, level = 1 # omitted ... @stats.each_pair |key, value| @mods[key] = ((value / 2 ) -5).floor end @mods.freeze end this solution if never want able change @mods again. trying set value result in error:
newchar.mods[:con] = 123 # runtimeerror: can't modify frozen hash inside class, can, however, overwrite @mods entirely.
to summarize, full class be:
class character attr_reader :str, :con, :dex, :wis, :int, :level, :mods, :stats def initialize str, con, dex, wis, int, cha, level = 1 @stats = { :str => str, :con => con, :dex => dex, :wis => wis, :int => int, :cha => cha } @mods = {} @level = level @stats.each_pair |key, value| @mods[key] = ((value / 2 ) -5).floor end @mods.freeze end end
Comments
Post a Comment