Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly setting instance variables with options hash in Ruby?

Tags:

I want to use an options hash as input to a method in Ruby, but is there a way to quickly set all eponymous variables (i.e having the same name) 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?

like image 508
mydoghasworms Avatar asked Nov 09 '12 06:11

mydoghasworms


People also ask

How do you declare an instance variable in Ruby?

The ruby instance variables do not need a declaration. This implies a flexible object structure. Every instance variable is dynamically appended to an object when it is first referenced. An instance variable belongs to the object itself (each object has its own instance variable of that particular class)

Can a Ruby module have instance variables?

In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.

How do you initialize a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

What is initialize method in Ruby?

The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.


1 Answers

def initialize(opts={})   opts.each { |k,v| instance_variable_set("@#{k}", v) } end 
like image 106
Casper Avatar answered Sep 28 '22 03:09

Casper