다음 해시가 있다고 가정 해 보겠습니다.
{ :foo => 'bar', :baz => 'qux' }
객체의 인스턴스 변수가되도록 키와 값을 어떻게 동적으로 설정할 수 있습니까?
class Example
  def initialize( hash )
    ... magic happens here...
  end
end
… 그래서 모델 내부에서 다음과 같이 끝납니다.
@foo = 'bar'
@baz = 'qux'
?
답변
당신이 찾고있는 방법은 instance_variable_set입니다. 그래서:
hash.each { |name, value| instance_variable_set(name, value) }
또는 더 간단히
hash.each &method(:instance_variable_set)
인스턴스 변수 이름에 “@”가 누락 된 경우 (OP의 예에서와 같이) 추가해야하므로 다음과 비슷합니다.
hash.each { |name, value| instance_variable_set("@#{name}", value) }
답변
h = { :foo => 'bar', :baz => 'qux' }
o = Struct.new(*h.keys).new(*h.values)
o.baz
 => "qux"
o.foo
 => "bar" 
답변
답변
send사용자가 존재하지 않는 인스턴스 변수를 설정하지 못하도록하는 방법 을 사용할 수도 있습니다 .
def initialize(hash)
  hash.each { |key, value| send("#{key}=", value) }
end
send클래스에 attr_accessor인스턴스 변수 와 같은 setter가있을 때 사용하십시오 .
class Example
  attr_accessor :foo, :baz
  def initialize(hash)
    hash.each { |key, value| send("#{key}=", value) }
  end
end