Ruby: 我如何在字符串中找到一个字母,如果它只是在所述字符串的开头?

Ruby: How do I find a letter in a string if only it is at the beginning of said string?

作为初级程序员,我想编写一个基本的 ABCs 应用程序。我只想看用户输入的第一个字母是否正确,单词的重置无关紧要。

puts "What word starts with the letter 'A'?"  
ans = gets.chomp  
puts "Correct!" if ans.include? .......

我不知道如何只评估用户输入的第一个字母。请帮忙!

puts "What word starts with the letter 'A'?"
ans = gets.chomp
puts "Correct!" if ans =~ /^a/i  # Case insensitive

您可以使用string.start_with?(arg)方法。 http://apidock.com/ruby/String/start_with%3F

puts "What word starts with the letter 'A'?"  
ans = gets.chomp                    # => 'apple'
"Correct!" if ans.start_with?('a')  # => true