红宝石中的货币转换器

时间:2013-11-01 16:25:11

标签: ruby operators converter currency

在创建转换器的过程中,我已经花了几个小时的时间。它应该从一种货币转换为另一种货币 这是代码:

def converter   
  puts "Enter the amount you wish to convert"  
  userAmount = gets   
  puts "Enter your choice: 1 for converting Qatari
  Riyals to US Dollars"   
  puts "Enter your choice: 2 for converting USD ollars to Qatari Riyals"   
  choiceConvert = gets
  while choiceConvert != 1 || choiceConvert != 2 do
    puts "please enter either 1 or 2"
    choiceConvertNew = gets
    choiceConvert = choiceConvertNew   
  end
  if choiceConvert == 1
    convertedAmount = userAmount / 3.65
    puts "Your choice is to convert #{userAmount} Qatari Riyals to US Dollars; 
      You get #{convertedAmount}  US Dollars" 
   else 
     convertedAmount = userAmount * 3.65
     puts "Your choice is to convert #{userAmount} US Dollars to Qatari Riyals; 
       You get #{convertedAmount} Qatari Riyals"  
   end    
end

converter

1 个答案:

答案 0 :(得分:1)

你试图在一个地方做太多尝试这个

def convert_currency(amount,choice)
  converted_amount = choice == 1 ? amount / 3.65 : amount * 3.65
  from, to = choice == 1 ? ["Qatari Riyals", "US Dollars"] : ["US Dollars","Qatari Riyals"]
  puts "Your choice is to convert #{sprintf('%.2f',amount)} #{from} to #{to}; You get #{sprintf('%.2f',converted_amount)} #{to}"
end

puts "Please Enter an Amount"
user_amount = gets.to_f
choice_convert = nil
while ![1,2].include?(choice_convert)
  puts "Enter your choice: 1 for converting Qatari Riyals to US Dollars"
  puts "Enter your choice: 2 for converting US Dollars to Qatari Riyals"
  choice_convert = gets.to_i
end
convert_currency(user_amount,choice_convert)