2012-09-12 45 views
3

我正在尝试查找数组中的特定字符,但此字符是由用户输入的。如何在Ruby中查找数组中的特定字符

我第一次订购了数组,然后要求用户输入特定的字符,然后我应该看到,如果这个角色在任何该阵列具有

出于某种原因的话存在,如果检查的时候人物的存在,我的“硬编码”的字符,它的工作原理,但如果我尝试去寻找字符,用户已经进入它不工作...

list = [ 'Mom' , 'Dad' , 'Brother' , 'Sister' ] 
puts ("Enter the character you would like to find"); 
character = gets 
for i in 0..(list.length - 1) 
if (list[i].include?(#{character})) 
puts ("Character #{character} found in the word #{list[i]}"); 
end 

非常感谢!

+0

调查使用的['each','select','find'和'任何?'](http://ruby-doc.org/core-1.9.3/Enumerable.html)代替'for'和在数组中使用索引搜索。 'For'不是惯用的Ruby。 –

回答

2

这是因为gets在字符串的末尾添加了\n。使用gets.chomp!,这样你就可以摆脱最后一个字符。

+0

非常感谢你!...制作了这个诀窍! –

+0

没问题,只要记得接受答案,如果你认为它有帮助,所以它可以帮助其他人。 – MurifoX

1

你应该使用“chomp”来摆脱输入行末尾的回车。另外,你也可以压缩你的代码。

list = [ 'Mom' , 'Dad' , 'Brother' , 'Sister' ] 
puts ("Enter the character you would like to find"); 
character = gets.chomp 
list.each do |e| 
    puts "Character #{character} found in the word #{e}" if e.include?(character) 
end 
+0

+1包含.each循环语法。 – KChaloux

相关问题