排序嵌套哈希错误“无法将符号转换为整数”

时间:2012-03-04 08:32:03

标签: ruby

我无法弄清楚为什么会失败?

1.9.3p0 :022 > hash = Hash.new
 => {} 
1.9.3p0 :023 > hash["jon"] = [:name=>"jon",:age=>22]
 => [{:name=>"jon", :age=>22}] 
1.9.3p0 :024 > hash["bob"] = [:name=>"bob",:age=>19]
 => [{:name=>"bob", :age=>19}] 
1.9.3p0 :025 > hash["sid"] = [:name=>"sid",:age=>25]
 => [{:name=>"sid", :age=>25}] 
1.9.3p0 :026 > hash
 => {"jon"=>[{:name=>"jon", :age=>22}], "bob"=>[{:name=>"bob", :age=>19}], "sid"=>[{:name=>"sid", :age=>25}]} 
1.9.3p0 :027 > hash.sort_by { |k, v| v[:age] }
TypeError: can't convert Symbol into Integer
    from (irb):27:in `[]'
    from (irb):27:in `block in irb_binding'
    from (irb):27:in `each'
    from (irb):27:in `sort_by'
    from (irb):27
    from /usr/share/ruby-rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :028 > hash.sort_by { |k, v| v[:age].to_i }
TypeError: can't convert Symbol into Integer
    from (irb):28:in `[]'
    from (irb):28:in `block in irb_binding'
    from (irb):28:in `each'
    from (irb):28:in `sort_by'
    from (irb):28
    from /usr/share/ruby-rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :029 >

本文建议它应该有效:http://www.rubyinside.com/how-to/ruby-sort-hash

1 个答案:

答案 0 :(得分:6)

您的语法已关闭。

hash["jon"] = [:name=>"jon",:age=>22] 

表示

hash["jon"] = [{:name=>"jon",:age=>22}]

所以将代码更改为:

hash = Hash.new
hash["jon"] = {:name=>"jon",:age=>22}
hash["bob"] = {:name=>"bob",:age=>19}
hash.sort_by { |k, v| v[:age] }