2017-05-04 117 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