From: Marnen Laibow-Koser Date: 2009-11-16T15:05:30+09:00 Subject: Re: Newbie question: Defining a numeric type Seebs wrote: > On 2009-11-16, Marnen Laibow-Koser wrote: >> Does it need to be a class of its own? > > I think it makes more sense that way. It's a category of objects which > have common additional methods they support, but which can be used in > nearly > any context where you could use an integer. Then they should most likely be Integers. Extend them either with module inclusion or by subclassing. > >> If you don't like the first solution, try: >> >> [:+, :*, :-, :/, :%].each do |op| >> define_method op {|other| self.to_i.send op, other} >> end >> >> You could wrap this in a module too. > > Could, but... > > The suggestion to try Forwardable got me to find SimpleDelegator, which > turns out to work beautifully. Yeah, but it's probably not conceptually right for this case. Have you been following the thread about using mixins rather than declaring new classes? > > Basically, I'm doing a roguelike mostly for fun and/or as a learning > exercise, and I wanted a way to encode "stats" -- things like strength > or intelligence, which characters have. Stats might have temporary > modifiers, or remember their highest previous value, or whatever... But > 90% of the time, you just want to refer to them and get the value > they currently have. Making the user write "player.str.current_value" > is annoying; I'd rather just use "player.str". So having that delegate > to an internal member which really is just an integer works; then, > whenever > that value changes, I point the delegator at it, and Everything Just > Works. If you use actual Integers as I suggested above, everything will Just Work with less effort, and your design will be clearer. > > -s Best, -- Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.