Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return anonymous object from a method in ruby

Tags:

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.?

like image 419
Muthukumar Avatar asked Oct 21 '16 08:10

Muthukumar


2 Answers

Openstruct?

require 'ostruct'

def helper
  OpenStruct.new(url: '', params: '')    
end
like image 167
Ursus Avatar answered Oct 16 '22 07:10

Ursus


Try this:

def helper
  Class.new do
    def url
      ''
    end
    def params
      ''
    end
  end.new
end
like image 39
yegor256 Avatar answered Oct 16 '22 06:10

yegor256