从ruby中的方法返回匿名对象

时间:2016-10-21 08:47:36

标签: ruby

如何从ruby中的方法返回匿名对象?

在下面的代码中,我将返回一个哈希值。

  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

有什么想法。?

2 个答案:

答案 0 :(得分:4)

Openstruct

require 'ostruct'

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

答案 1 :(得分:1)

尝试一下:

def helper
  Class.new do
    def url
      ''
    end
    def params
      ''
    end
  end.new
end