简体   繁体   中英

Ruby Loop through some attributes of an object

In Rails, I have a class name User , in which I just want to look at :name, :address, :age

I would like to write a piece of code that's something like:

user = User.new
[name, address, age].zip(["Name", "Address", 10]).each do |attribute, val|
  user.attribute = val
end

The thing is I don't know how to do it properly, since user.attribute is obviously not a valid line. In other word, is there anyway so that user.attribute gets evaluated as user.name , user.address , user.age depends on the loop?

You should use send method

user.send "#{attribute}=", val

If attribute is, say, :name , then the line above is equivalent to

user.name = val

Actually I can do it this way:

[name, address, age].zip(["Name", "Address", 10]).each do |attribute, val|
    user[attribute] = val
end

This way works, too

user.send(:name) would be the same as calling user.name , so you may want to try that.

user = User.new
[name, address, age].zip(["Name", "Address", 10]).each do |attribute, val|
  user.write_attribute(attribute, val)
end

But that's what I'd write:

user = User.new
user.attributes = {name => "Name", address => "Address", age => 10}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM