V
Vincent Foley
Hi everyone,
I finished playing yet another game of Chrono Trigger the other day,
and I thought I would look at how I could implement a simple Character
system in Ruby. I have the following initialize method, but I would
like to be sure it's not extremely bad style:
class Character
attr_accessor :strength, :magic, :defense, :magic_defense
def initialize(args = {})
args.each do |k, v|
instance_variable_set("@#{k}", v) if respond_to?(k)
end
methods.grep(/\w=$/).each { |setter|
getter = setter[0..-2]
if send(getter).nil?
send(setter, 0)
end
}
end
end
So, if I added a :critical_rate accessor, I wouldn't need to modify
anything else in the initialize method. Also, I don't want nil in any
attribute. Is this good style? Are there other (maybe better) ways to
accomplish this? Thank you.
I finished playing yet another game of Chrono Trigger the other day,
and I thought I would look at how I could implement a simple Character
system in Ruby. I have the following initialize method, but I would
like to be sure it's not extremely bad style:
class Character
attr_accessor :strength, :magic, :defense, :magic_defense
def initialize(args = {})
args.each do |k, v|
instance_variable_set("@#{k}", v) if respond_to?(k)
end
methods.grep(/\w=$/).each { |setter|
getter = setter[0..-2]
if send(getter).nil?
send(setter, 0)
end
}
end
end
So, if I added a :critical_rate accessor, I wouldn't need to modify
anything else in the initialize method. Also, I don't want nil in any
attribute. Is this good style? Are there other (maybe better) ways to
accomplish this? Thank you.