I'm working with an unsorted array of hashes, where the order of the hashes within the array is not important. Each hash has an :id primary key, which is used to find it within the array. The design of this system is outside of my control.

I must design a read-modify-write system for:

  1. Looking up the hash (by :id) within the array.

  2. Performing modifications to other keys within the hash.

  3. Saving this hash back to the array.

Now, it's not hard at all to do this and get it working. But what is the Ruby answer?

Thanks!

有帮助吗?

解决方案

a = [{id: 1, x: :y}, {id: 2, x: :z}, ...]

Looking up id 2:

a.find{|h| h[:id] == 2} # => {:id=>2, :x=>:z}

Changing the value for :x attribute for id 2:

a.find{|h| h[:id] == 2}[:x] = :w

其他提示

If you want to change the hash, all you need to do is find it:

h = arr.find { |h| h[:id] == id }
h[:change_me] = 'changed!'

If you want to replace it, you better dup it:

h = arr.delete_if { |h| h[:id] == id }.first.dup
h[:change_me] = 'changed!'
arr << h
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top