Muthukumar Muthukumar - 1 month ago 18
Ruby Question

Return anonymous object from a method in ruby

How can I return an anonymous object from a method in ruby.?

In the following code, I am returning an hash.

def process
source = helper

# I am able to get the value as an hash
puts source[:url]
puts source[:params]

# But I wonder if there is a way to get it as an object, so that I can use the dot notation
# puts source.url
# puts source.params
end

def helper
url = ''
params = ''
return {url: url, params: params}
end


Any thoughts.?

Answer

Openstruct?

require 'ostruct'

def helper
  OpenStruct.new(url: '', params: '')    
end