我知道 Forwardable#def_delegate 如何与对象的方法一起工作,但是是否有类似的方法将方法名称转发到哈希键。喜欢:
hash = { some_value: 42, other_value: 31415 }
def_delegate :hash, :some_value, :other_value
调用object.some_value
应该返回42
PS: def 和 class eval 是一种方法,但是有更好的方法吗?
最佳答案
这对 OpenStruct
来说是件好事,它基本上将哈希包装在一个对象中。
2.2.1 :001 > require 'ostruct'
=> true
2.2.1 :002 > s = OpenStruct.new(a: 1, b: 2)
=> #<OpenStruct a=1, b=2>
2.2.1 :003 > s.a
=> 1
2.2.1 :004 > s.c = 3
=> 3
如果你想严格控制可用的方法,Struct
允许您创建小型动态类。
2.2.1 :001 > hash = {a: 1, b: 2}
=> {:a=>1, :b=>2}
2.2.1 :002 > struct = Struct.new(*hash.keys)
=> #<Class:0x007fd104b32888>
2.2.1 :003 > instance = struct.new(*hash.values)
=> #<struct a=1, b=2>
2.2.1 :004 > instance.a = 3
=> 3
2.2.1 :005 > instance.c
NoMethodError: undefined method `c' for #<struct a=3, b=2>
关于ruby-on-rails - 使用带有哈希的 def_delegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812568/