0

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?

4 Answers 4

5

You should use send method

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

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

user.name = val
Sign up to request clarification or add additional context in comments.

3 Comments

I'd use send as last resort, Rails provides write_attribute(attribute, value).
Oh yes, he did actually mention rails. Just not in the tags :)
check again :-p. It's ok to show send as the basic metaprogramming method, but given that the OP is using rails we can mention both (and another way in my answer).
1

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

Comments

1

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

Comments

1
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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.