如果情景不适用于红宝石

时间:2017-04-30 12:49:40

标签: ruby

我刚开始学习红宝石。有人能让我知道为什么这不运行?谢谢。

greeting_preference = true

until greeting_preference

Puts "How should I greet you?"

greeting_preference = gets.chomp

if greeting_preference == "Bonjour!"
    puts "Bonjour!"
    greeting_preference = true

if greeting_preference == "Hola!"
    puts "Hola!"
    greeting_preference = true

if greeting_preference == "in Afrikaans"
    puts "Hallo!"
    greeting_preference = true
else
    puts "Uh, hi?"
end

4 个答案:

答案 0 :(得分:3)

看起来你只是end until。您的ifif-else也需要end

if greeting_preference == "Bonjour!"
    puts "Bonjour!"
    greeting_preference = true
end

的if-else

if condition
  puts "something"
else
  puts "something else"
end

答案 1 :(得分:2)

将if {else

括起来end
greeting_preference = true
while greeting_preference
    puts "How should I greet you?"
    greeting_preference = gets.chomp
    if greeting_preference == "Bonjour!"
        puts "Bonjour!"
        greeting_preference = true
    end
    if greeting_preference == "Hola!"
        puts "Hola!"
        greeting_preference = true
    end
    if greeting_preference == "in Afrikaans"
        puts "Hallo!"
        greeting_preference = true
    else
        puts "Uh, hi?"
    end
end

更好地使用case声明:

greeting_preference = true
while greeting_preference
    puts "How should I greet you?"
    msg = gets.chomp
    puts case msg
        when "Bonjour!" 
            "Bonjour!"
        when "Hola!" 
            "Hola!"
        when "in Afrikaans" 
            "Hallo!"
        else
            greeting_preference = false
            "Uh, hi?"
        end
end

答案 2 :(得分:1)

您可以用任何语言编写FORTRAN。 :)

Hash您的代码会更容易。它基本上是一个字典,您可以在其中定义键(问候语)和值(答案)。如果找不到钥匙,请再次询问!

greetings = {
  'Bonjour!' => 'Bonjour!',
  'Hola!' => 'Hola!',
  'in Afrikaans' => 'Hallo!'
}

puts 'How should I greet you?'
puts "(possible choices are #{greetings.keys})"

until greeting = greetings[gets.chomp]
  puts 'Uh, hi?'
end

puts greeting

输出:

How should I greet you?
(possible choices are ["Bonjour!", "Hola!", "in Afrikaans"])
Hello?
Uh, hi?
Hi!
Uh, hi?
Hola!
Hola!

答案 3 :(得分:0)

你必须结束until语句。

until语句条件为false时执行代码,所以直到!greeting_preference

   greeting_preference = false

   until greeting_preference do

   puts "How should I greet you?"

   greeting_preference = gets.chomp

   if greeting_preference == "Bonjour!"
      puts "Bonjour!"
      greeting_preference = true
   elsif
      greeting_preference == "Hola!"
      puts "Hola!"
      greeting_preference = true
   elsif
      greeting_preference == "in Afrikaans"
      puts "Hallo!"
      greeting_preference = true
   else
      puts "Uh, hi?"
   end

   end