Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个红宝石哈希,比如说
h={name: "john", age: "23"}
它不是一个对象,只是一个从对象创建的散列。我想在访问对象时使用方法属性访问它的值。IE:
h.name => "john" h.age => 23
是否有可能做到这一点?
在您的情况下,使用openstruct会很方便
require 'ostruct' h = OpenStruct.new(name: "john", age: "23") h.name #=> "john" h.age #=> 23
也许这就是你要找的
item = Struct.new(:id, :name) item.new(1, 'Name')