mydoghasworms mydoghasworms - 1 year ago 26
Ruby Question

Quickly setting instance variables with options hash in Ruby?

I want to use an options hash as input to a method in Ruby, but is there a way to quickly set all synonymous variables instead of setting each individually?

So instead of doing the following:

class Connection
def initialize(opts={})
@host = opts[:host]
@user = opts[:user]
@password = opts[:password]
@project = opts[:project]
# ad nauseum...

is there a one-liner that will assign each incoming option in the hash to the variable with the same name?

def initialize(opts={})
  opts.each { |k,v| instance_variable_set("@#{k}", v) }