0

有没有更好的方法来缩短这些重复的 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
4

2 回答 2

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

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

于 2013-07-08T01:59:56.063 回答
0

是的,使用 lambda 进行哈希调用并查找哈希,然后调用代码块。

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

于 2013-07-07T23:57:16.803 回答