AndreZimpel AndreZimpel - 7 months ago 31
Ruby Question

Dot notation to arrays

I got a string

'tileBlock.tag.title'
and an object like this:

[
"title"=>"headline",
"body"=>"body text",
"link"=>"#",
"tileBlock"=>{"title"=>"Home", "tag"=>{"title"=>"home", "id"=>45}, "active"=>true}
]


Is there a way to transform
'tileBlock.tag.title'
to something like
'object[:tileBlock][:tag][:title]
?

Answer

You can use Enumerable#inject, take str="tileBlock.tag.title".

str.split(".").inject(object) { |m, x| m[x] }
Comments