2

I want to achieve something like this:

object = SomeObj.new do
  instancevar = "value"
  anotherone  = "valuenew"
end

object.instancevar => "value"

But I have no idea how to design initialize method, I had something like this:

class Klass 
  def initialize(info = {})
    info[:property] = "value"
  end
end

I want to pass some hash in constructor to set instance variables, but also I would like to provide instantiating with block, but have no idea how to achieve this.

4

3 に答える 3

3

こちら からインストールできるRuby 2.x では、次の操作を実行できます。

class SomeObj
  def initialize **named_parameters
    named_parameters.each_pair { |symbol, value|
      instance_variable_set "@#{symbol}", value
      singleton_class.class_eval { attr_accessor symbol }
    }
  end
end

o = SomeObj.new( foo: 42, bar: 43 )
o.foo #=> 42
o.bar #=> 43
于 2013-05-16T13:06:33.457 に答える