0

I have a user object which i access like this.. user.email, user.first_name

Now I want to loop through each and return a message based on the current key in loop somewhat like this.

[user.first_name, user.email, user.last_name].each do |key|
      puts "#{key} is required"
 end

The above works but loops through values instead of fields. so will do this below but how to prepend user to keys and get values inside array?

[first_name, email, last_name].each do |key|
 #inside here I want to prepend the user to the keys so that I can access like user.key 

 puts "#{user.key} is required" 
end

If this was a string we can concatenate but how to deal with this here as its a method call?

2
  • 1
    Are you asking how to use key as a method call on user? Commented Mar 29, 2017 at 19:29
  • @jvillian yes... Commented Mar 29, 2017 at 19:30

3 Answers 3

2

With ActiveRecord you can access properties via the [] method:

[ :first_name, :email, :last_name ].each do |key|
  unless (user[key])
    puts "#{key} is required"
  end
end

This generally a lot safer than the send approach because it's not calling arbitrary methods.

Sign up to request clarification or add additional context in comments.

Comments

1

You can simply do:

user.send(key)

Comments

-1
[first_name, email, last_name].each do |key|
 puts user.send(key)
end

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.