开发者

getting variable value dynamically

开发者 https://www.devze.com 2023-02-21 19:23 出处:网络
I have the following class class User attr_accessor :name, :age, :address def initialize() self.name = \"new user\"

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消