简体   繁体   中英

Ruby exact string match

so I'm teaching myself Ruby, and I made a simple heads or tails game. The user types in 'h' to choose heads and 't' to select tails. Under normal use, everything works fine, but unfortunately if the user types in 'th' they can win every time. How do I only reward exact string matches?

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

choice.match('t') will be truthy for any string where there is t anywhere in it. Use choice == 't' . Or, if you really want to be using regular expressions, choice.match(/\\At\\Z/) (match beginning, t and end of the string).

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.

Updated code is as follows:

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

Also, you can refer to the document " http://ruby-doc.org/core-2.2.2/Object.html#method-i-eql-3F ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM