user502052
user502052

Reputation: 15259

How to make 'attr_reader' or 'attr_writer' for all class variables at one time?

I am using Ruby on Rails 3 and, since I have a declared a class with a lot of variables, I would declare all 'attr_reader' or 'attr_writer' for those class variables at one time.

I tryed

class Persone
  attr_reader :all

  def initialize(name, surname, ...)
    @name = name
    @surname = surname
    ... # A lot of variables!
  end
end

but that doesn't work.

Upvotes: 4

Views: 2203

Answers (6)

Peter Ryan
Peter Ryan

Reputation: 51

the instance_variable block had a typo in Chris Wouters example...

instance_variables.each do |var|
    eval "def #{var.to_s.sub('@', '')}\n #{var}; end"
  end

Upvotes: 0

Chris Wouters
Chris Wouters

Reputation: 11

The answer may be late, 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

Upvotes: 1

juandebravo
juandebravo

Reputation: 200

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

Upvotes: 0

zetetic
zetetic

Reputation: 47548

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

Upvotes: 4

Emmanuel Valle
Emmanuel Valle

Reputation: 332

I thing you should use:

attr_accesor :name, :surname, ...

def initialize(name, surname, ...)
  @name = name
  @surname = surname
  ...
end

This way you get a setter and a getter in only one step, but you still have to enum all that variable names.

Upvotes: 2

Mladen Jablanović
Mladen Jablanović

Reputation: 44090

Take a look at Struct class:

Persone = Struct.new :name, :surname, :address

p = Persone.new 'John', 'Smith', '12 Street 345'
puts p.address

Upvotes: 1

Related Questions