gpt4 book ai didi

ruby - 一种指定和初始化 map 值类型的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:57 25 4
gpt4 key购买 nike

我想计算一行文本中的所有单词。我正在使用 map 来执行此操作,使用单词作为键,使用整数作为值。我不知道如何告诉 Ruby 所有的值都是整数。它迫使我在我的迭代器 block 中放置一个丑陋的分支:

# in the constructor
@individual_words = {}

def count_words_from( text_line )
text_line.each do |line|
line.scan(/\p{Word}+/)
.reject{ |string| string =~ /\d/ }
.each do |word|
if @individual_words[ word ] == nil then # This is ugly
@individual_words[ word ] = 1 # This is ugly as well
else
@individual_words[ word ] += 1
end
end
end
end

简单来说,我想做类似 Java 行的事情:

Map<String, Integer> individualWords;

避免必须将单词第一次出现的类型从 Nil 更改为 Integer

最佳答案

您可以像这样在哈希中设置默认值:

individual_words = Hash.new(0)

那么当你遇到一个词时,无论它的键是否在散列中,你所要做的就是:

individual_words[word] += 1

关于ruby - 一种指定和初始化 map 值类型的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12751120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com