흥미로운 점은 인덱스 버킷과 스토리지 해시를 관리하는 버킷 샤딩 시스템에 시나리오가 있다는 것입니다. 상호 연관성은 생성 된 UUID이며 분산되어 있기 때문에 새 버킷에 고유 참조가 필요하다는 확신이 필요합니다. .Ruby에서 해시의 키에 사용되는 특정 객체를 얻는 편리한 방법은 무엇입니까?
이 연습의 초기에 나는 해시에서 문자열을 키로 사용하면 속도록 채워지고 자동으로 동결되어 코드가 생성 될 수 있음을 보장하기 때문에 SecureRandom.uuid (문자열 생성)로 생성 된 모든 키를 고정 시키도록 코드를 최적화하기 시작했습니다. 변경되지 않습니다. (문자열이고 얼지 않는 경우).
대부분의 경우 적극적으로 이것을 수행하는 것이 쉽습니다. 특히 새로운 UUID의 경우 (실제로이 프로젝트에 많은 가치가 필요합니다.)하지만 어떤 경우에는이 값을 넘는 값으로 해시에 접근해야하는 경우가 있습니다. 네트워크를 구축하고 획득하면 키로 나타나는 문자열을 일관되게 사용하기 위해 오히려 둔한 조회 메커니즘을 사용하십시오.
내 목표는 여러 노드에서 거대한 데이터 세트를 유지하면서 가능한 한 키 및 색인 저장소의 오버 헤드를 줄이고 버킷 시스템이기 때문에 같은 UUID를 여러 번 참조 할 수 있기 때문입니다. 같은 참조를 사용하는 것이 도움이됩니다.
다음은 간단한 (ish) 형식의 문제를 보여주는 코드입니다. 나는 문자열 값이 같은 (키 이름과 관련된 값이 아닌) 키에 대한 기존의 객체 참조를 얻기위한보다 최적의 편리한 메커니즘이 있는지 묻는 것이다.
require 'securerandom'
index = Hash.new
store = Hash.new
key = 'meh'
value = 1
uuid = SecureRandom.uuid
store[uuid] = value
index[key] = uuid
# obtained from elsewhere
uuid = uuid.dup.freeze
uuid = store.find{|k,_| k == uuid }.first
store[uuid] = value
index[key] = uuid
store.each_key { |x| puts "Store reference for value of #{x} #{x.object_id}"}
index.each_value { |x| puts "Index reference for #{x} #{x.object_id}" }
출력 :
012,351Ruby dups and freezes strings if used for keys in hashes
This produces different IDs
Store reference for value of bd48a581-95e9-452e-b8a3-602d92d47011 70209306325780
Index reference for bd48a581-95e9-452e-b8a3-602d92d47011 70209306325880
If inconsistencies in ID occur then Ruby attempts to preserve the use of the frozen key so if it happens in one area take care
This produces different IDs
Store reference for value of bd48a581-95e9-452e-b8a3-602d92d47011 70209306325780
Index reference for bd48a581-95e9-452e-b8a3-602d92d47011 70209306325880
If you start with a clean slate and a frozen key you can overcome it if you freeze the string before use
This is clean so far and produces the same object
Store reference for value of bd48a581-95e9-452e-b8a3-602d92d47011 70209306325880
Index reference for bd48a581-95e9-452e-b8a3-602d92d47011 70209306325880
But if the same value for the key comes in (possibly remote) then it becomes awkward
This produces different IDs
Store reference for value of bd48a581-95e9-452e-b8a3-602d92d47011 70209306325880
Index reference for bd48a581-95e9-452e-b8a3-602d92d47011 70209306325000
So you get into oddities like this to ensure you standarise values put in to keys that already exist
This cleans up and produces same IDs but is a little awkward
Store reference for value of bd48a581-95e9-452e-b8a3-602d92d47011 70209306325880
Index reference for bd48a581-95e9-452e-b8a3-602d92d47011 70209306325880
* * 참고로 잘못된 –
' Hash.new'는 그 자체로 거의 사용되지 않습니다. 대신'{}'을 사용하십시오. – tadman
물론 명시 적으로 장황하고 사실상 파서 성능 측면에서 제외하면 의미가 거의 없습니다. 코멘트는 구약입니다. –