将用户输入与数组中的元素进行比较而忽略空格

时间:2018-01-17 06:43:07

标签: ruby string

我想将用户输入player与数组players中的元素进行比较:

players = ["KYRIE IRVING", "KEVIN DURANT", "KAWHI LEONARD"]

如果player位于players而忽略player中的空格,那么我想继续前进;否则,我希望它显示错误信息。例如,如果player"KYRIE IRVING""Kyrie Irving""kyrie irving""kyrieirving",我想继续前进。

以下代码不适用于"kyrieirving"

def valid_player(player, fan, players, vote_history)
  until players.include?(player) || **players.gsub(/\s+/, "").include?(player)**
    puts "\n   Oops! That's not a valid player. Please try again."  
    print "\n   Fan #{fan}: "  
    player = gets.chomp.upcase 
  end 
 vote_history << player
end

我可以创建另一个包含没有空格的玩家所有元素的数组,然后与之比较。我还可以创建一个块,其中gsub方法适用于数组的每个元素。我认为这是一个比这两个选项中任何一个更清晰的解决方案。

3 个答案:

答案 0 :(得分:0)

以下内容与kyrieirving相符:

re = /KYRIE IRVING/mix

接下来将与KYRIE IRVING,Kyrie Irving,kyrie irving相匹配:

re = /KYRIE IRVING/mi

x表示忽略空格...你可以准备两个带有x标志的正则表达式而另一个没有并在迭代通过数组时应用两者。否则你将不得不申请你在帖子中提到的作为FORBIDDEN的东西(我认为会更好):)

re = /KYRIE IRVING/mi
str = 'KYRIE IRVING, Kyrie Irving, kyrie irving, or kyrieirving,'

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

答案 1 :(得分:0)

几点

  • put in ruby​​包含换行符,因此如果你调用puts,你不需要用换行符开始你的字符串。

  • 我发现以小写字母而不是大写字母更容易存储所有内容。更容易阅读。

  • 我会使用递归来检查有效的响应,而不是循环。

类似的东西:

def valid_player(fan, players, vote_history)
    player = gets.strip
    player_no_spc = player.gsub(" ","").downcase
    players_no_spc = players.map{ |s| s.gsub(" ","")}

    if players_no_spc.include?(player_no_spc)
       return vote_history << player
    else
       puts "Oops! That's not a valid player. Please try again."
       puts "Fan #{fan}: "
       valid_player(fan, players, vote_history)
    end
end

答案 2 :(得分:0)

players = %w|KYRIEIRVING KEVINDURANT KAWHILEONARD|
player_to_check = "Kyrie IRVING"
if p = players.detect? { |p| p == player_to_check.delete(' ').upcase }
  puts "Found: #{p}"
else
  puts "Oops!"
end