更新:修正了参数错误,删除了elsif上的elsif input.include? != false
并替换为elsif input == false
UPDATE2:代码运行正常,精确翻译并为短语提供正确的翻译
require 'yaml'
def translate
translations = YAML.load_file 'spanish.yml'
puts "Enter word or phrase to be translated to English, press 'Q' to quit:"
input = gets.chomp
case
when translations[input]
puts "The translation to English is: #{translations[input]}"
when input =~ /q/i
exit
else
puts "Invalid word or phrase redirecting..."
translate
end
end
translate
有没有办法让译员也可以翻译俄语?这是俄罗斯的YAML文件:
и: and, though
в: in, at
не: not
он: he
на: on, it, at, to
я: I
что: what, that, why
тот: that
быть: to be
с: with and, from, of
а: while, and, but
весь: all, everything
это: that, this, it
как: how, what, as, like
我会做与翻译西班牙语相同的事情,但是我会加载russian.yaml
而不是加载西班牙语,或者我必须做出另一个定义,例如:
def russian_translate
translations = YAML.load_file 'russian.yml'
puts "Please enter the phrase to translate"
etc...
答案 0 :(得分:1)
首先,可能不应该在文本文件中使用Ruby语法编写的哈希值。 Ruby人通常使用YAML:
es_en.yml:
a: to
abajo: down
el_abanico: fan
然后可以将此文件加载到哈希:
require 'yaml'
translations = YAML.load_file 'es_en.yml'
#⇒ {
# "a" => "to"
# "abajo" => "down"
# "el_abanico" => "fan"
# }
现在是时候处理input
:
input = gets.chomp
case
when translations[input]
puts "The translation is: #{translations[input]}"
when input =~ /^q$/i # input is a single “q” letter
exit
else "Translation not found"
end
你可能想把它放在循环中。