如何使用OpenStruct的marshal_load实用程序?它似乎没有按预期工作.
文档提供了这个示例,但它似乎不起作用.
require 'ostruct'
event = OpenStruct.new
hash = { 'time' => Time.now, 'title' => 'Birthday Party' }
event.marshal_load(hash)
event.title # => nil
Run Code Online (Sandbox Code Playgroud)
如果不是这样,我如何将哈希加载到OpenStruct(不使用构造函数)?
对于上下文:我正在从YAML文件加载哈希并将其加载到OpenStruct子类的现有实例中.
这个答案显示NSDictionary的哈希值是字典中的条目数.(类似地,NSArray的散列是它的长度.)答案继续建议创建一个类别以提供更好的散列实现.
如果您需要更准确的哈希值,可以在Obj-C类别中自行提供.
但是当我尝试这个时,无论如何它似乎都使用了原始的哈希实现.
我们有标题 NSDictionary+Hash.h
#import <Foundation/Foundation.h>
@interface NSDictionary (Hash)
- (NSUInteger)hash;
@end
Run Code Online (Sandbox Code Playgroud)
并执行NSDictionary+Hash.m
:
#import "NSDictionary+Hash.h"
@implementation NSDictionary (Hash)
- (NSUInteger)hash
{
// Based upon standard hash algorithm ~ https://stackoverflow.com/a/4393493/337735
NSUInteger result = 1;
NSUInteger prime = 31;
// Fast enumeration has an unstable ordering, so explicitly sort the keys
// https://stackoverflow.com/a/8529761/337735
for (id key in [[self allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
id value = [self objectForKey:key];
// okay, so copying Java's hashCode a bit:
// …
Run Code Online (Sandbox Code Playgroud)