Ruby精确字符串匹配

时间:2015-08-19 00:59:56

标签: ruby

所以我在教自己Ruby,我做了一个简单的头或尾游戏。用户输入'h'选择head,'t'选择tails。在正常使用情况下,一切正常,但不幸的是,如果用户键入'th',他们每次都可以获胜。我如何只奖励确切的字符串匹配?

puts "~~~~~ HEADS OR TAILS ~~~~~"
print "Choose: Heads or Tails? (h,t): "
choice = gets.to_s
flip = rand(0..1)

if !choice.match('h') && !choice.match('t')
  puts "oops"
elsif flip === 0
  puts "The coin flipped as heads!"
  puts "You chose: " + choice.to_s
  if choice.match('h')
    puts "YOU WIN!"
  elsif !choice.match('h')
    puts "YOU LOSE."
  end
elsif flip === 1
  puts "The coin flipped as tails"
  puts "You chose: " + choice.to_s
  if choice.match('t')
    puts "YOU WIN!"
  elsif !choice.match('t')
    puts "YOU LOSE."
  end
end

2 个答案:

答案 0 :(得分:1)

对于任何位置都有choice.match('t')的字符串,

t将是真实的。使用choice == 't'。或者,如果您真的想要使用正则表达式,choice.match(/\At\Z/)(匹配开头,t和字符串结尾)。

答案 1 :(得分:0)

To fix your issue, you can update your code with below changes:

 1. Replace match with eql? in the above code. This will perform
    case-sensitive string comparisons in the program. In order to
    ensure, for case-insensitive comparisons, you can use 'casecmp'
    method defined in ruby. 
 2.  Also, you can enhance your code by replacing
    to_s with chomp() method it will strip off \r,\n.

更新后的代码如下:

puts "~~~~~ HEADS OR TAILS ~~~~~"
print "Choose: Heads or Tails? (h,t): "
choice = gets.chomp
flip = rand(0..1)

if !choice.eql?('h') && !choice.eql?('t')
  puts "oops"
elsif flip === 0
  puts "The coin flipped as heads!"
  puts "You chose: " + choice
  if choice.match('h')
    puts "YOU WIN!"
  elsif !choice.match('h')
    puts "YOU LOSE."
  end
elsif flip === 1
  puts "The coin flipped as tails"
  puts "You chose: " + choice
  if choice.match('t')
    puts "YOU WIN!"
  elsif !choice.match('t')
    puts "YOU LOSE."
  end

另外,您可以参考文档" http://ruby-doc.org/core-2.2.2/Object.html#method-i-eql-3F"。