ruby字符串来哈希转换 [英] ruby string to hash conversion
本文介绍了ruby字符串来哈希转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的字符串,
str = "uu@p, xx@m, yy@n, zz@m"
我想知道如何将给定的字符串转换为散列。 (即我的实际要求是,有多少个值(在@符号之前)有m,n和p,我不想计数,我需要一个确切的值)。输出结果会更好,
I want to know how to convert the given string into a hash. (i.e my actual requirement is, how many values (before the @ symbol) have the m, n and p. I don't want the counting, I need an exact value). The output would be better like this,
{"m" => ["xx", "zz"], "n" => ["yy"], "p" => ["uu"]}
推荐答案
IRB会话的直接复制/过去:
Direct copy/past of an IRB session:
>> str.split(/, /).inject(Hash.new{|h,k|h[k]=[]}) do |h, s|
.. v,k = s.split(/@/)
.. h[k] << v
.. h
.. end
=> {"p"=>["uu"], "m"=>["xx", "zz"], "n"=>["yy"]}
这篇关于ruby字符串来哈希转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文