Not directly, no. One option is to use OpenStruct from the Ruby standard library.
require "ostruct" class Foo extend Forwardable delegate :@data, :some_value, :other_value def initialize(hash) @data = OpenStruct.new(hash) end end hash = { some_value: 42, other_value: 31415 } foo = Foo.new(hash) foo.some_value
A simpler option is to simply delegate the method :[] , but this is not so pretty:
class Foo extend Forwardable delegate :@data, :[] def initialize(hash) @data = hash end end hash = { some_value: 42, other_value: 31415 } foo = Foo.new(hash) foo[:some_value]
If this is not the case, always define_method :
[ :some_value, :other_value ].each do |meth| define_method(meth) { @data[meth] } end
Or method_missing :
def method_missing(meth, *args, &block) return @data[meth] if @data.key?(meth) super end def respond_to_missing?(meth, *args) @data.key?(meth) || super end
source share