Я хочу заменить заявление case
в рубине с Hash
. Но Hash, кажется, сначала вызывает значение по умолчанию, когда я пытаюсь найти другие ключи в хэше.Заменить регистр с хешем в рубине
def perform_operation_one
puts 'Performing operation ONE'
end
def perform_operation_two
puts 'Performing operation TWO'
end
def exit_program
puts 'Program is exiting now'
exit(0)
end
def perform_operation(operation_code)
case operation_code
when 1
perform_operation_one
when 2
perform_operation_two
else
exit_program
end
end
Я заменил выше case
заявление с Hash
def perform_operation(operation_code)
operations = Hash.new exit_program #Default value if no operation is present in operations corresponding to operation_code key
operations[1] = perform_operation_one
operations[2] = perform_operation_two
operations[operation_code]
end
Теперь, когда я выполняю следующее:
perform_operation(2)
Ожидаемый результат:
Performing operation TWO
Выходной ток:
Program is exiting now
Могу ли я спросить, почему вы хотите заменить инструкцию 'case'? Он выглядит намного чище ИМО (хотя я буду писать каждый «когда» в одной строке, т. Е. «Когда 1 затем выполняет_операцию_он»). – Stefan