我正在尝试计算球队的获胜次数,但是我的代码中已经计算出球队名称中每个字母的实例。
wins = 0
puts "Please enter a team name to check"
teamname = gets.chomp.to_s
tencentbeernight = IO.readlines("winners.txt").to_s
wins = tencentbeernight.count(teamname)
printf "The %2s have won %2i times" % [teamname, wins]
如何计算团队的名称?
答案 0 :(得分:1)
count
计算单个字符的数量,而不是字符串的实例。
尝试:
wins = tencentbeernight.scan(teamname).length
这将使用teamname
作为正则表达式并计算它出现的次数。
答案 1 :(得分:0)
将IO::readlines返回的数组转换为字符串,然后计算字符串在该字符串中出现的次数可以起作用,但这不是任何有经验的Rubiest都会采用的方法。
首先,让我们创建一个文件"winners.txt"
。
arr = ["Raiders", "Bears", "bearskin rug", "Chargers", "my bugbears", "bears"]
str = arr.join("\n")
#=> "Raiders\nBears\nbearskin rug\nChargers\nmy bugbears\nbears"
filename = "winners.txt"
File.write(filename, str)
#=> 53 (characters written)
并获得团队名称:
team = gets.chomp
#=> "bears"
请参见IO#write。 1
问题中提倡的方法和另一个答案中提供的方法如下:
array = IO.readlines(filename)
#> ["Raiders\n", "Bears\n", "bearskin rug\n", "Chargers\n", "my bugbears\n", "bears"]
str = array.to_s
#=> "[\"Raiders\\n\", \"Bears\\n\", \"bearskin rug\\n\", \"Chargers\\n\", \"my bugbears\\n\", \"bears\"]"
a = str.scan(team)
#=> ["bears", "bears", "bears"]
a.size
#=> 3
这是不正确的。我们可以解决这些问题,但是更常规的方法如下:
team = gets.downcase.chomp
#=> "bears"
a = File.readlines(filename)
#=> ["raiders\n", "bears\n", "bearskin rug\n", "chargers\n", "my bugbears\n", "bears"]
a.count { |s| s.downcase.match?(/\b#{team}\b/) }
#=> 2
给出正确答案,因为a[1]
和a[-1]
(仅那些元素)被匹配。正则表达式为:“匹配word break(\b
),后跟team
的值,然后再换一个字符”。
但是,我们可以对此进行改进。无需创建临时数组a
。取而代之的是,我们使用IO::foreach,它逐行读取文件,并且在不带块的情况下返回一个枚举数:
enum = File.foreach(filename)
#=> #<Enumerator: File:foreach("winners.txt")>
通过将enum
转换为数组,我们可以看到它们将生成的值:
enum.to_a
#=> ["raiders\n", "\n", "bears\n", "\n", "bearskin rug\n", "\n", "chargers\n",
# "\n", "my bugbears\n", "\n", "bears\n"]
继续
enum.count { |s| s.downcase.match?(/\b#{team}\b/) }
#=> 2
一个通常会链接这两种方法:
File.foreach(filename).count { |s| s.downcase.match?(/\b#{team}\b/) }
#= 2
1我已经使用File
作为类IO
中定义的某些方法的接收者。这通常是可行的,因为File.superclass #=> IO
。