문제

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