Find and replace specific hash and it's values within array

后端 未结 1 797
清歌不尽
清歌不尽 2021-01-21 11:54

What is the most efficient method to find specific hash within array and replace its values in-place, so array get changed as well?

I\'ve got this code so far, but in a

相关标签:
1条回答
  • 2021-01-21 13:00

    This will do what you're after looping through the records only once:

    array.each { |hash| hash[:parameters][:omg] = "triple omg" if hash[:id] == 1 }
    

    You could always expand the block to handle other conditions:

    array.each do |hash| 
      hash[:parameters][:omg] = "triple omg" if hash[:id] == 1
      hash[:parameters][:omg] = "quadruple omg" if hash[:id] == 2
      # etc
    end
    

    And it'll remain iterating over the elements just the once.

    It might also be you'd be better suited adjusting your data into a single hash. Generally speaking, searching a hash will be faster than using an array, particularly if you've got unique identifier as here. Something like:

    { 
      1 => {
        parameters: {
          omg: "lol"
        },
        options: {
          lol: "omg"
        }
      },
      2 => {
        parameters: {
          omg: "double lol"
        },
        options: {
          lol: "double omg"
        }
      } 
    }
    

    This way, you could just call the following to achieve what you're after:

    hash[1][:parameters][:omg] = "triple omg"
    

    Hope that helps - let me know how you get on with it or if you have any questions.

    0 讨论(0)
提交回复
热议问题