我正在尝试运行计算器程序但由于某种原因它正在跳过代码的某些部分。这是我的整个红宝石代码:
# require yaml file
require 'yaml'
MESSAGES = YAML.load_file('calculator_messages.yml')
LANGUAGE = 'en'
def messages(message, lang='en')
MESSAGES[lang][message]
end
def prompt(key)
message = messages(key, LANGUAGE) # make sure the "messages" method is declared above this line
Kernel.puts("=> #{message}")
end
def integer?(input)
input.to_i.to_s == input
end
def float?(input)
input.to_f.to_s == input
end
def valid_number?(input)
integer?(input) || float?(input)
end
def operation_to_message(op)
word = case op
when '1'
'Adding'
when '2'
'Subtracting'
when '3'
'Multiplying'
when '4'
'Dividing'
end
word
end
prompt('welcome')
name = ''
loop do
name = Kernel.gets().chomp()
if name.empty?()
prompt('valid_name')
else
break
end
end
prompt("Hi #{name}!")
loop do # main loop
number1 = ''
loop do
prompt('first_number')
number1 = Kernel.gets().chomp()
if valid_number?(number1)
break
else
prompt('not_a_valid_number')
end
end
number2 = ''
loop do
prompt('second_number')
number2 = Kernel.gets().chomp()
if valid_number?(number2)
break
else
prompt('not_a_valid_number')
end
end
operator_prompt = <<-MSG
What operation would you like to perform?
1) add
2) subtract
3) multiply
4) divide
MSG
prompt(operator_prompt)
operator = ''
loop do
operator = Kernel.gets().chomp()
if %w(1 2 3 4).include?(operator)
break
else
prompt('choose_number_range')
end
end
prompt("#{operation_to_message(operator)} the two numbers")
result = case operator
when '1'
number1.to_i() + number2.to_i()
when '2'
number1.to_i() - number2.to_i()
when '3'
number1.to_i() * number2.to_i()
else
number1.to_f() / number2.to_f()
end
prompt("The answer is: #{result}")
prompt('next_step')
answer = Kernel.gets().chomp()
break unless answer.downcase().start_with?('y')
end
prompt('goodbye_msg')
现在,这里是它跳过的具体代码:
1.显示名称
prompt("Hi #{name}!")
2.显示添加,减去等消息
prompt("#{operation_to_message(operator)} the two numbers")
3。最后是在结果变量中打印实际答案的部分。
result = case operator
when '1'
number1.to_i() + number2.to_i()
when '2'
number1.to_i() - number2.to_i()
when '3'
number1.to_i() * number2.to_i()
else
number1.to_f() / number2.to_f()
end
prompt("The answer is: #{result}")
你知道为什么它会跳过这些代码吗?
答案 0 :(得分:2)
问题:据我所知,您的prompt
消息会尝试翻译,但可能无法找到例如“嗨,菲利克斯。”
您可以通过更改message
功能
def messages(message, lang='en')
MESSAGES[lang][message] || "NO TRANSLATION FOUND"
end
再次观察输出。
<强>更新强> 由于OP证实了理论并在评论中要求“解决方案”,最便宜的可能就是这个:
def messages(message, lang='en')
# Look up translation, default to untranslated message.
MESSAGES[lang][message] || message
end