Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting variable value dynamically

I have the following class

class User
  attr_accessor :name, :age, :address

  def initialize()
    self.name = "new user"
    self.age = 19
    self.address = "address" 
  end  


end

What I want if to have a method to get the assigned values to the attributes. Means, I have another method to get all the method names inside the above class

methods = self.public_methods(all = false)

and I can get the method name from that (I mean the getter of name etc..) and I want a way to pass that method name (which I have it as string) and get the return value of the method

Ex:

when I pass 'name' as the method name I should be able to get 'new user' as the value

hope I made my question clear, thanks in advance

** Please note, i have to use this way as my class has so many attributes and it has so many inherited classes. So accessing each and every attr individually is not possible :D

like image 928
sameera207 Avatar asked Apr 02 '11 07:04

sameera207


People also ask

Can a variable be dynamic?

A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.

How will you dynamically pass the name variable as a parameter?

In JavaScript, dynamic variable names can be achieved by using 2 methods/ways given below. eval(): The eval() function evaluates JavaScript code represented as a string in the parameter. A string is passed as a parameter to eval(). If the string represents an expression, eval() evaluates the expression.


1 Answers

That’s what send is for:

user = User.new
user.name        # => "new user"
user.send(:name) # => "new user"

getters = user.public_methods(false).reject { |m| m =~ /=$/ }
getters.each { |m| puts user.send(m) }

Using instance_variable_get is another option if you don’t have an accessor method:

user.instance_variable_get(:@name) # => "new user"

Using public_methods to get a list of attributes could be dangerous, depending on how you determine which methods to call. Instead, you could create your own class method which both defines the accessor and stores the attribute name for future use:

class User
  class << self
    attr_reader :fields

    def field (*names)
      names.flatten.each do |name|
        attr_accessor name
        (@fields ||= []) << name
      end
    end
  end

  field :name
  field :age
  field :address
end

user = User.new
user.name    = "Me"
user.age     = 22
user.address = "1234"

user.class.fields.each do |field|
  puts user.send(field)
end
like image 105
Todd Yandell Avatar answered Sep 21 '22 17:09

Todd Yandell