Question

I have an array of hashes of hash like following:

[
        {
            "value"=>10,
            "inner_hash"=>{
                "name"=>"cc",
            }
        },
        {
            "value"=>14,
            "inner_hash"=>{
                "name"=>"vv",
            }
        },
        {
            "value"=>12,
            "inner_hash"=>{
                "name"=>"mm",
            }
        },
        {
            "value"=>11,
            "inner_hash"=>{
                "name"=>"pp",
            }
        }
    ]

I want to sort this array based on the inner_hash's value of name key. How do I do it in Ruby?

Expected output:

[
        {
            "value"=>10,
            "inner_hash"=>{
                "name"=>"cc",
            }
        },
        {
            "value"=>12,
            "inner_hash"=>{
                "name"=>"mm",
            }
        },
        {
            "value"=>11,
            "inner_hash"=>{
                "name"=>"pp",
            }
        },
        {
            "value"=>14,
            "inner_hash"=>{
                "name"=>"vv",
            }
        }
    ]
Was it helpful?

Solution

foo.sort_by { |x| x['inner_hash']['name'] }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top