2016-06-14 79 views
0

我的任務是檢查用戶的給定輸入是否包含字母"c""s"。我用一個管理,但我根本不知道寫這個的正確方法。如何檢查數組是否包含X或Y

我知道問題是"s" || "c"

print 'What can we do for you?' 
user_input = gets.chomp 
user_input.downcase! 

if user_input.empty? 
    puts 'Well you will have to write something...!' 
elsif user_input.include? 's' || 'c' 
    puts "We got ourselves some 's's and some 'c's" 
    user_input.gsub!(/s/, 'th') 
    user_input.tr!('c', 's') 
    puts "The Daffy version, #{user_input}!" 
else 
    print "Nope, no 's' or 'c' found" 
end 

回答

2

簡單

elsif user_input.include?("s") || user_input.include?("c") 

或類似

%w(s c).any? { |command| user_input.include? command } 
+1

完美的人:)非常感謝!它如此簡單,但這讓我粘在屏幕上大約一個小時。我昨天剛剛開始了紅寶石。 –

2

這是正則表達式都很好,其中一個很好的例子:

user_input =~ /[sc]/ 
0

您可以使用正則表達式

user_input[/s|c/] 
1

或:

(user_input.split('') & %w(s c)).any? 
+2

'user_input'是一個字符串,爲了這個工作,我們應該'拆分'它:'(user_input.split('')&%w(s c))any?',但是這種方法是無效的。 – mudasobwa

+0

@mudasobwa是的,你說的對,我的錯。 –

+0

@CarySwoveland 我以爲我把它刪除了 謝謝你提醒我! –

0

沒有正則表達式:

user_input.count('sc') > 0 
相關問題