在Ruby中重构重复的case语句

时间:2013-07-07 23:54:56

标签: ruby refactoring

有没有更好的方法来缩短这些重复的switch case语句?或许,一个更具可读性的解决方案?

isTyping = true
accMenu = ['Balance', 'Withdraw', 'Deposit', 'Exit']
account = Account.new('Jason Bourne', 278430, 100.0)
while isTyping do
  accMenu.each_with_index { |str, i| print i+1, '. ', str, "\n" }
  print 'Enter account option: '
  accOption = gets.to_i
  case accOption                                                                                                                                                         
  when 1
    puts "Account Balance: #{account.balance}"
  when 2
    puts 'How much to withdraw from account? '
    debit = gets.to_f
    account.withdraw(debit)
  when 3
    puts 'How much to deposit from account? '
    credit = gets.to_f
    account.deposit(credit)
  when 4
    isTyping = false
  else
    puts 'Invalid account option, try again!'
  end
end

2 个答案:

答案 0 :(得分:1)

accMenu = %w[Balance Withdraw Deposit Exit]
account = Account.new("Jason Bourne", 278430, 100.0)
loop do
  accMenu.each.with_index(1){|str, i| puts "#{i}. #{str}"}
  print "Enter account option: "
  case gets.to_i
  when 1
    puts "Account Balance: #{account.balance}"
  when 2
    puts "How much to withdraw from account?"
    account.withdraw(gets.to_f)
  when 3
    puts "How much to deposit from account?"
    account.deposit(gets.to_f)
  when 4
    break
  else
    puts "Invalid account option, try again!"
  end
end

使用魔术数字并不好。您可能希望通过执行以下操作使代码更具可读性:

  case accMenu[gets.to_i]
  when "Balance"
    puts "Account Balance: #{account.balance}"
  when "Withdraw"
    puts "How much to withdraw from account?"
    account.withdraw(gets.to_f)
  when "Deposit"
    puts "How much to deposit from account?"
    account.deposit(gets.to_f)
  when "Exit"
    break
  else
    puts "Invalid account option, try again!"
  end

但你可能更喜欢第一个,我不知道。

答案 1 :(得分:0)

是的,使用lambda创建一个哈希来调用并对哈希进行查找,然后调用代码块。

http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/