如何使用将字符串作为参数的方法,并将其变为散列?
如何使用将字符串作为参数的方法,并将其转换为显示键的散列:作为单词和值:作为单词出现在字符串中的次数?如何使用将字符串作为参数的方法,并将其变为散列?
def my_string(string)
end
my_string("This is my string, or could be any string.")
我在想,我将不得不string.split(" ")
,并以某种方式使用数组。
def my_string(string)
string.split(" ")
string_hash = {}
string.each_with_index do |element, index|
string_hash[index] = element
end
end
my_string("This is my string, or could be any string.")
def my_string(str)
str.downcase.scan(/[[:alpha:]]+/).each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }
end
str = "A cat, a dog and another cat."
my_string str
#=> {"a"=>2, "cat"=>2, "dog"=>1, "and"=>1, "another"=>1}
这使用类方法Hash::new接受一个参数为默认值的形式。这仅仅意味着如果散列h = Hash.new(d)
没有密钥k
,则h[k]
返回默认值d
,这里是0
。 (散列不变)
步骤如下。通过枚举生成
s = str.downcase
#=> "a cat, a dog and another cat."
a = s.scan(/[[:alpha:]]+/)
#=> ["a", "cat", "a", "dog", "and", "another", "cat"]
e = a.each_with_object(Hash.new(0))
#=> #<Enumerator: ["a", "cat", "a", "dog", "and", "another", "cat"]:
# each_with_object({})>
的第一个值,并传递给块,并且块变量s
和h
被分配的值。
s,h = e.next
#=> ["a", {}]
s #=> "a"
h #=> {}
h[s] += 1
# h["a"] = h["a"] + 1 => h["a"] = 0 + 1 => h["a"] = 1
当红宝石看到h["a"] += 1
(在解析时),她做的第一件事就是展开对h["a"] = h["a"] + 1
。由于h
最初为空(因此没有密钥"a"
),所以在等号右侧的h["a"]
返回默认值0
。继续,
s,h = e.next
#=> ["cat", {"a"=>1}]
s #=> "cat"
h #=> {"a"=>1}
h[s] += 1
# h["cat"] = h["cat"] + 1 => h["cat"] = 0 + 1 => h["cat"] = 1
s,h = e.next
#=> ["a", {"a"=>1, "cat"=>1}]
s #=> "a"
h #=> {"a"=>1, "cat"=>1}
h[s] += 1
# h["a"] = h["a"] + 1 => h["a"] = 1 + 1 => h["a"] = 2
h #=> {"a"=>2, "cat"=>1}
这次h
有一个关键"a"
,在平等的右侧,所以h["a"]
返回该键,1
值。
其余的步骤是相似的。
最后,一个适用于21世纪的正则表达式:) –
'Enumerable#count_by'确实是一个缺失的部分。 ( –
)为什么'split'而不是'scan',虽然?后者似乎更合适,意图明智。 –
你为此编写的代码在哪里?你的代码的输出是什么?什么不准确地工作? – Surya
到目前为止,我还没有真正走得很远。如果有办法做到这一点,我试图看到任何新人。 – Joseph
另一种方式来做这个'string.split.group_by(&:本身).transform_values(&:size)' –