I use Ruby on Rails 3, and since I have a declared class with a lot of variables, I would declare all the attr_reader or attr_writer attributes for these class variables in one go.
I tried
class Persone attr_reader :all def initialize(name, surname, ...) @name = name @surname = surname ... # A lot of variables! end end
but it does not work.
class Persone INSTANCE_VARS = [:name,:surname] attr_reader *INSTANCE_VARS def initialize(*params) params.each_with_index do |param,index| instance_variable_set("@"+INSTANCE_VARS[index].to_s,param) end end end
I want to use:
attr_accesor :name, :surname, ... def initialize(name, surname, ...) @name = name @surname = surname ... end
This way you get the setter and receiver in just one step, but you still need to list all the variable names.
Take a look at the Struct class:
Struct
Persone = Struct.new :name, :surname, :address p = Persone.new 'John', 'Smith', '12 Street 345' puts p.address
The answer may be belated, but late is better than never:
class Persone def initialize(name, surname, ...) @name = name @surname = surname ... # A lot of variables! instance_variables.each do |var| eval "def #{var.to_s.sub('@', '')}; #{i}; end" end end end
class Persone VARS = [:name, :surname, ...] VARS.each{|var| attr_reader var } def initialize(params) params.each_pair{|key,value| self.instance_variable_set("@#{key}".to_sym, value } end end
variable block instance had a typo in Chris Waters example ...
instance_variables.each do |var| eval "def #{var.to_s.sub('@', '')}\n #{var}; end" end
Source: https://habr.com/ru/post/1341260/More articles:Is there an attribute to limit the type to which a user attribute can be applied? - typesShould Post and Comment be in Post Aggregate or should they be their aggregates? - repositoryLarge file transfer with sockets - javaThe column is not valid in the select list because it is neither contained in the aggregate function nor in the GROUP BY clause - sqlAndroid SDK Connect to the web server on the host - androidNeed help choosing a database server - c ++Visual Studio 2010 - fix "use" function? - c #Getting the last row in each group? - sqlProblem loading NSMutablearray value in table view? - uitableviewfind what kind of click - iphoneAll Articles