2017-05-04 118 views
0

环路我只想做一个简单的循环:麻烦与红宝石

我想是这样的:

loop do 
    puts "What hotel would you like to pick" 

    hotelCode = gets.chomp.downcase #gets user input and puts it lowerCase 

    if hotelCode != "a" || hotelCode != "b" || hotelCode != "c" || hotelCode != "d" # if user input is not a,b,c,d break 
     break 
    else 
     puts "How many nights would you like to stay" 
     nights = gets.chomp.to_i 
    end 
end #end while loop 

puts "congrats u got out" 

在我的代码,它只是不断打破循环,无论我做什么。我错过了明显的东西吗?

+2

您正在使用'||'。你想'&&'。如果它是“a”,那么它是!=“b”,所以条件仍然是正确的。 –

+1

...让我再也不说这个了!\ – sublimeaces

回答

3

也许你想,如果输入的是选择那些没有你的循环结束。所以

if hotelCode != "a" && hotelCode != "b" & hotelCode != "c" && hotelCode != "d" 

更好

if !["a", "b", "c", "d"].include?(hotelCode) 

更好

if !%w(a b c d).include?(hotelCode) 

unless %w(a b c d).include?(hotelCode) 
+0

有趣的是,我喜欢if!%w(a b c d).include?(hotelCode)的外观..如果hotelCode不包含b c或d,但是!%w是什么? – sublimeaces

+0

@sublimeaces:'%w'是一个字符串数组文字。在irb中试试,'%w(abcd)' –

+0

@sublimeaces更多信息[here](https://ruby-doc.org/core-2.3.0/doc/syntax/literals_rdoc.html#label-Percent+字符串)。 – Gerry

1

从你的代码,它应该是这样的:

loop do 
    puts "What hotel would you like to pick" 
    hotelCode = gets.chomp.downcase #gets user input and puts it lowerCase 
    if hotelCode != "a" && hotelCode != "b" && hotelCode != "c" && hotelCode != "d" # if user input is not a,b,c,d break 
     break 
    else 
     puts "How many nights would you like to stay" 
     nights = gets.chomp.to_i 
    end 
end #end while loop 
puts "congrats u got out" 
1
if hotelCode != "a" || hotelCode != "b" || ... 

如果酒店代码为 “B”,这将打破在第一个条件。如果它是“a”,它会在第二秒中断。这种情况是不可能满足的。

要么使用

if hotelCode != "a" && hotelCode != "b" && ... 

if hotelCode == "a" || hotelCode == "b" || ... 
    # handle valid hotel 
else 
    break 
end 

简单的布尔数学:)或者更好的是,使用的熊属的例子之一。

+0

感谢您回复的时间 – sublimeaces

0

我会建议使用String类的方法。这里有几个,按我的个人喜好(从高到低)排序。

hotel_code !~ /[abcd]/ 

hotel_code =~ /[^abcd]/ 

!"abcd".include?(hotel_code) 

"abcd".index(hotel_code).nil? 

hotel_code.count("abcd").zero? 

hotel_code.delete("abcd") == hodel_code 

"abcd".delete(hotel_code) == "abcd" 

第二返回一个整数( “truthy”)或nil( “falsy”);其他人返回truefalse