Unable to use dot syntax for ruby hash
OpenStruct will work well for a pure hash, but for hashes with embeded arrays or other hashes, the dot syntax will choke. I came across this solution, which works well without loading in another gem: https://coderwall.com/p/74rajw/convert-a-complex-nested-hash-to-an-object basic steps are:
data = YAML::load(File.open("your yaml file"))
json_data = data.to_json
mystr = JSON.parse(json_data,object_class: OpenStruct)
you can now access all objects in mystr using dot syntax.
If you don't want to install any gems, you can try to use the Ruby's native Struct
class and some Ruby tricks, like the splat operator.
# regular hashes
customer = { name: "Maria", age: 21, country: "Brazil" }
customer.name
# => NoMethodError: undefined method `name' for {:name=>"Maria", :age=>21, :country=>"Brazil"}:Hash
# converting a hash to a struct
customer_on_steroids = Struct.new(*customer.keys).new(*customer.values)
customer_on_steroids.name
#=> "Maria"
Please note that this simple solution works only for single-level hashes. To make it dynamic and fully functional for any kind of Hash
, you'll have to make it recursive to create substructs inside your struct.
You can also store the Struct as if it was a class.
customer_1 = { name: "Maria", age: 21, country: "Brazil" }
customer_2 = { name: "João", age: 32, country: "Brazil" }
customer_3 = { name: "José", age: 43, country: "Brazil" }
Customer = Struct.new(*customer_1.keys)
customer_on_steroids_1 = Customer.new(*customer_1.values)
customer_on_steroids_2 = Customer.new(*customer_2.values)
customer_on_steroids_3 = Customer.new(*customer_3.values)
Read more about Ruby Struct class.
Hash
does not have dot-syntax for it's keys. OpenStruct
does:
require 'ostruct'
hash = {:name => 'John'}
os = OpenStruct.new(hash)
p os.name #=> "John"
NOTE: Does not work with nested hashes.
Ruby hashes don't work like this natively, but the HashDot gem would work for this.
HashDot allows dot notation syntax use on hashes. It also works on json strings that have been re-parsed with JSON.parse
.
require 'hash_dot'
hash = {b: {c: {d: 1}}}.to_dot
hash.b.c.d => 1
json_hash = JSON.parse(hash.to_json)
json_hash.b.c.d => 1