如何使用将字符串作为参数的方法,并将其转换为哈希?

时间:2017-09-29 14:46:56

标签: ruby hash

如何使用将字符串作为参数的方法,并将其转换为显示键的哈希:作为单词和值:作为单词出现在字符串中的次数?

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.")

1 个答案:

答案 0 :(得分:3)

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)没有密钥kh[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({})>

第一个值由枚举器生成并传递给块,块变量sh被赋值。

s,h = e.next
  #=> ["a", {}]
s #=> "a"
h #=> {}
h[s] += 1
  # h["a"] = h["a"] + 1 => h["a"] = 0 + 1 => h["a"] = 1

当Ruby看到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

其余步骤类似。

相关问题