РЕДАКТИРОВАТЬ Следуя рекомендациям VictorMoroz и @ mu:
class Actions
def initialize
@people = []
end
def cmd_add(name)
@people << name
end
def cmd_remove
puts "Goodbye"
end
def cmd_other
puts "Do Nothing"
end
def people
p @people
end
def run_command(cmd, *param)
cmd = 'cmd_' + cmd.to_s.downcase
send(cmd, *param) if respond_to?(cmd)
end
end
act = Actions.new
act.run_command('add', 'joe')
act.run_command(:ADD, 'jill')
act.run_command('ADD', 'jack')
act.run_command('people') # does nothing
act.people
Или
class Actions
ALLOWED_METHODS = %w( add remove other )
def initialize
@people = []
end
def add(name)
@people << name
end
def remove
puts "Goodbye"
end
def other
puts "Do Nothing"
end
def people
p @people
end
def run_command(cmd, *param)
cmd = cmd.to_s.downcase
send(cmd, *param) if ALLOWED_METHODS.include?(cmd)
end
end
act = Actions.new
act.run_command('add', 'joe')
act.run_command(:add, 'jill')
act.run_command('add', 'jack')
act.run_command('people') # does nothing
act.people